处理 Promise.all 中的错误

2024-04-14

我有一系列正在解决的 PromisePromise.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.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();
});

但这并不能解决问题。

--

Edit:

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

Node Express服务器链

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 调用(route.async 调用)

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

.catch for Promise.all之前.then似乎已经达到了捕获原始承诺中的任何错误的目的,但然后将整个数组返回到下一个.then.


Promise.all要么全有,要么全无。一旦数组中的所有承诺都解决,它就会解决,或者一旦one他们中的一些人拒绝了。换句话说,它要么使用所有已解析值的数组进行解析,要么以单个错误拒绝。

有些图书馆有一个叫做Promise.when,我理解会等待all数组中的 Promise 要么解析,要么拒绝,但我不熟悉它,ES6 中也没有。

你的代码

我同意这里其他人的观点,你的修复应该有效。它应该使用可能包含成功值和错误对象混合的数组进行解析。在成功路径中传递错误对象是不寻常的,但假设您的代码期望它们,我认为这没有问题。

我能想到为什么它“无法解析”的唯一原因是它在您没有向我们展示的代码中失败,并且您没有看到任何关于此的错误消息的原因是因为这个承诺链没有以最终终止抓住(就你向我们展示的内容而言)。

我冒昧地从您的示例中提取出“现有链”,并用 catch 终止该链。这可能不适合您,但对于阅读本文的人来说,始终返回或终止链很重要,否则潜在的错误,甚至编码错误,将被隐藏(我怀疑这就是这里发生的情况):

Promise.all(state.routes.map(function(route) {
  return route.handler.promiseHandler().catch(function(err) {
    return err;
  });
}))
.then(function(arrayOfValuesOrErrors) {
  // handling of my array containing values and/or errors. 
})
.catch(function(err) {
  console.log(err.message); // some coding error in handling happened
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

处理 Promise.all 中的错误 的相关文章

随机推荐