我有一个promise数组,我用Promise.all(arrayOfPromises)来解析它;

我继续承诺链。大概是这样的

existingPromiseChain = existingPromiseChain.then(function() {
  var arrayOfPromises = state.routes.map(function(route){
    return route.handler.promiseHandler();
  });
  return Promise.all(arrayOfPromises)
});

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
  // do stuff with my array of resolved promises, eventually ending with a res.send();
});

我想添加一个catch语句来处理一个单独的promise,以防它出错,但是当我尝试时,promise。all返回它找到的第一个错误(忽略其余的错误),然后我就不能从数组中的其余承诺(没有错误)中获得数据。

我试过做一些像…

existingPromiseChain = existingPromiseChain.then(function() {
      var arrayOfPromises = state.routes.map(function(route){
        return route.handler.promiseHandler()
          .then(function(data) {
             return data;
          })
          .catch(function(err) {
             return err
          });
      });
      return Promise.all(arrayOfPromises)
    });

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
      // do stuff with my array of resolved promises, eventually ending with a res.send();
});

但这并不能解决问题。

谢谢!

--

编辑:

下面的答案是完全正确的,代码被破坏是由于其他原因。如果有人感兴趣,这是我最终得出的解决方案……

节点快速服务器链

serverSidePromiseChain
    .then(function(AppRouter) {
        var arrayOfPromises = state.routes.map(function(route) {
            return route.async();
        });
        Promise.all(arrayOfPromises)
            .catch(function(err) {
                // log that I have an error, return the entire array;
                console.log('A promise failed to resolve', err);
                return arrayOfPromises;
            })
            .then(function(arrayOfPromises) {
                // full array of resolved promises;
            })
    };

API调用(路由。异步调用)

return async()
    .then(function(result) {
        // dispatch a success
        return result;
    })
    .catch(function(err) {
        // dispatch a failure and throw error
        throw err;
    });

把。catch作为承诺。在.then之前的所有内容似乎都用于从原始的promise中捕获任何错误,但随后将整个数组返回到下一个.then

谢谢!


当前回答

不幸的是,我没有足够的声誉来评论(或者做任何事情,真的),所以我把这篇文章作为对Eric的回答的回应。

executor函数也可以是异步函数。然而,这通常是一个错误,原因如下: 如果异步执行器函数抛出错误,错误将被丢失,不会导致新构造的Promise被拒绝。这可能会使调试和处理某些错误变得困难。 如果Promise执行函数使用await,这通常表明实际上不需要使用新的Promise构造函数,或者可以缩小新的Promise构造函数的作用域。

由此解释了为什么promise不应该使用异步执行器函数

相反,您应该选择promise . allsettle(),就像Asaf在这里建议的那样。

其他回答

正如@jib所说,

的承诺。要么全部,要么一无所有。

不过,您可以控制某些“允许”失败的承诺,我们希望继续进行。

为例。

  Promise.all([
    doMustAsyncTask1,
    doMustAsyncTask2,
    doOptionalAsyncTask
    .catch(err => {
      if( /* err non-critical */) {
        return
      }
      // if critical then fail
      throw err
    })
  ])
  .then(([ mustRes1, mustRes2, optionalRes ]) => {
    // proceed to work with results
  })

不幸的是,我没有足够的声誉来评论(或者做任何事情,真的),所以我把这篇文章作为对Eric的回答的回应。

executor函数也可以是异步函数。然而,这通常是一个错误,原因如下: 如果异步执行器函数抛出错误,错误将被丢失,不会导致新构造的Promise被拒绝。这可能会使调试和处理某些错误变得困难。 如果Promise执行函数使用await,这通常表明实际上不需要使用新的Promise构造函数,或者可以缩小新的Promise构造函数的作用域。

由此解释了为什么promise不应该使用异步执行器函数

相反,您应该选择promise . allsettle(),就像Asaf在这里建议的那样。

新回答

const results = await Promise.all(promises.map(p => p.catch(e => e)));
const validResults = results.filter(result => !(result instanceof Error));

未来承诺API

Chrome 76: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled 现在就可以下载https://www.npmjs.com/package/promise.allsettled获取。在某些浏览器中,allsettle是与浏览器一起预安装的。为了心安,下载这个软件包是值得的。TypeScript没有allsettle的默认定义。

我们可以在单个承诺级别处理拒绝,所以当我们在结果数组中获得结果时,被拒绝的数组索引将是未定义的。我们可以根据需要处理这种情况,并使用剩余的结果。

这里我拒绝了第一个承诺,所以它没有定义,但是我们可以使用第二个承诺的结果,它在索引1处。

const manyPromises = Promise.all([func1(), func2()])。然后(result => { console.log(结果[0]);/ /定义 console.log(结果[1]);/ / func2 }); 函数func1() { return new Promise((res, rej) => rej('func1'))。Catch (err => { Console.log('错误处理',err); }); } 函数func2() { return new Promise((res, rej) => setTimeout(() => res('func2'), 500)); }

如果您可以使用q库https://github.com/kriskowal/q 它有q. allsettle()方法可以解决这个问题 您可以根据每个承诺的状态来处理它,可以是完全提交的,也可以是拒绝的 所以

existingPromiseChain = existingPromiseChain.then(function() {
var arrayOfPromises = state.routes.map(function(route){
  return route.handler.promiseHandler();
});
return q.allSettled(arrayOfPromises)
});

existingPromiseChain = existingPromiseChain.then(function(arrayResolved) {
//so here you have all your promises the fulfilled and the rejected ones
// you can check the state of each promise
arrayResolved.forEach(function(item){
   if(item.state === 'fulfilled'){ // 'rejected' for rejected promises
     //do somthing
   } else {
     // do something else
   }
})
// do stuff with my array of resolved promises, eventually ending with a res.send();
});