【问题标题】:How to use bluebird .all and .reflect effectively?如何有效地使用 bluebird .all 和 .reflect?
【发布时间】:2016-06-15 18:48:34
【问题描述】:

我有一系列承诺,我需要等到所有承诺都被履行或拒绝。 这就是我正在做的事情

var = [promiseA,promiseB,promiseC]      
    Promise.all(promises.map(function(promise) {
     
       return promise.reflect();
    
    })).each(function(inspection) {
     
    if (inspection.isFulfilled()) {
    
    console.log("A promise in the array was fulfilled   with",inspection.value());
       
   } else {

      console.error("A promise in the array was 
       rejected with",  inspection.reason());
     
    }
       
 })

上面的代码打印出每个promise的已完成或拒绝的值。在我的例子中,这里的每个promise都返回一个成功或错误的json。我需要使用 .then() 之类的函数获取所有成功的 json 值。

当我尝试使用 .then 获取值时

Promise.all(promises.map(function(promise) {
      
   return promise.reflect();
   
 })).then(data){
//_settledValue gives me the json value either success json or error json
   console.log('data[0]::::’+JSON.stringify(data[0]._settledValue));    
}.

我将如何忽略错误 json 并在这里只取成功 json? 谁能帮我解决这个问题?

【问题讨论】:

  • 如果你的异步方法的返回结果并没有真正抛出错误,而是返回一个表明这是一个错误的字符串,你可能必须通过检查该字符串来自己处理,如 Promises无法阅读。想到Array.filter

标签: javascript promise bluebird


【解决方案1】:

按照其他人的建议使用Array.filterBluebird.filter

Bluebird.all(promises.map(function(promise) {
          
  return promise.reflect();
       
}))
  .filter(function(promise) {return promise.isFulfilled();})
  // or .then(promises => promises.filter(/*...*/))
  .then(function (data) {
     // only successful ones are available here...
  });

【讨论】:

  • 但是如果您还想查看所有异常情况怎么办?
猜你喜欢
  • 1970-01-01
  • 2017-04-29
  • 2017-03-22
  • 2015-06-10
  • 2012-05-07
  • 2011-05-31
  • 2015-11-25
  • 2021-09-04
  • 1970-01-01
相关资源
最近更新 更多