Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - 处理Promise.all中的错误(Handling errors in Promise.all)

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

(我有一个用Promise.all(arrayOfPromises);解决的Promises数组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();
});

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).

(我想添加一个catch语句来处理单个promise,以防万一出错,但是当我尝试时, Promise.all返回它发现的第一个错误(忽略其余错误),然后我无法从其余错误中获取数据数组中的promise(没有错误)。)

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

But that doesn't resolve.

(但这并不能解决。)

Thanks!

(谢谢!)

--

(-)

Edit:

(编辑:)

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 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 Call (route.async call)

(API调用(route.async调用))

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

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

(把.catchPromise.all的之前.then似乎已经担任了从原来的承诺捕捉任何错误,但随后返回整个数组的下一个目的.then)

Thanks!

(谢谢!)

  ask by Jon translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Promise.all is all or nothing.

(Promise.all是全部或全部。)

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.

(换句话说,它要么使用所有已解析值的数组进行解析,要么使用单个错误进行拒绝。)

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.

(有些库中有一个叫做Promise.when东西,据我了解,它会等待数组中的所有 Promise.when解析或拒绝,但是我并不熟悉,ES6中也没有。)

Your code

(您的密码)

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).

(我能想到它“无法解决”的唯一原因是,它在代码中失败,您没有向我们显示;而您没有看到有关此消息的任何错误消息,是因为该诺言链没有以final结尾捕获(就您向我们展示的内容而言)。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...