处理Promise.all中的错误 [英] Handling errors in Promise.all

查看:363
本文介绍了处理Promise.all中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列Promise,我正在使用Promise.all(arrayOfPromises)解析;

I have an array of Promises that I'm resolving with Promise.all(arrayOfPromises);

我继续继承承诺链。看起来像这样

I go on to continue the promise chain. Looks something like this

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返回它找到的第一个错误(忽略其余的错误),然后我无法从数组中的其余promises中获取数据(没有错误)。

I want to add a catch statement to handle an individual promise in case it errors, but when I try, Promise.all returns the first error it finds (disregards the rest), and then I can't get the data from the rest of the promises in the array (that didn't error).

我尝试过做类似的事情。

I've tried doing something like ..

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();
});

但这不能解决。

谢谢!

-

编辑:

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

What the answers below said were completely true, the code was breaking due to other reasons. In case anyone is interested, this is the solution I ended up with ...

Node Express服务器链

Node Express Server Chain

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调用)


API Call (route.async call)

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

在.then之前放置.catch for Promise.all似乎是为了捕获任何内容来自原始承诺的错误,但随后将整个数组返回到下一个。然后

Putting the .catch for Promise.all before the .then seems to have served the purpose of catching any errors from the original promises, but then returning the entire array to the next .then

谢谢!

推荐答案

Promise.all 全有或全无。一旦阵列中的所有承诺解决,它就会解析,或者只要一个拒绝它们就拒绝。换句话说,它可以使用所有已解析值的数组进行解析,也可以使用单个错误进行拒绝。

Promise.all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.

某些库具有名为 Promise的内容。当时,我理解它会等待所有承诺在数组中解析或拒绝,但我不熟悉它,而且它不在ES6中。

Some libraries have something called Promise.when, which I understand would instead wait for all promises in the array to either resolve or reject, but I'm not familiar with it, and it's not in ES6.

您的代码

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

I agree with others here that your fix should work. It should resolve with an array that may contain a mix of successful values and errors objects. It's unusual to pass error objects in the success-path but assuming your code is expecting them, I see no problem with it.

我能想到为什么它的唯一原因不解决是因为你没有向我们展示代码失败以及你没有看到任何关于这个错误消息的原因是因为这个承诺链没有以最后的捕获终止(就你所说的而言)无论如何都向我们展示。)

The only reason I can think of why it would "not resolve" is that it's failing in code you're not showing us and the reason you're not seeing any error message about this is because this promise chain is not terminated with a final catch (as far as what you're showing us anyway).

我冒昧地将你的例子中的现有链分解出来并用一个捕获来终止链。这可能不适合你,但对于阅读本文的人来说,重要的是始终要么返回或终止链,否则潜在的错误,甚至编码错误都会被隐藏(这是我怀疑在这里发生的事情):

I've taken the liberty of factoring out the "existing chain" from your example and terminating the chain with a catch. This may not be right for you, but for people reading this, it's important to always either return or terminate chains, or potential errors, even coding errors, will get hidden (which is what I suspect happened here):

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
});

这篇关于处理Promise.all中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆