Promise.all找到被拒绝的承诺 [英] Promise.all find which promise rejected

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

问题描述

在我的代码中,我使用 Promise.all()在一些承诺全部完成后异步运行代码。有时,一个承诺会失败,我不知道为什么。 我想知道哪个承诺失败。将回调作为第二个参数传递给 .then 方法并没有多大帮助,我知道 承诺拒绝但哪个承诺拒绝。

In my code, I am using Promise.all() to run code asynchronously once some promises have all fulfilled. Sometimes, one promise will fail, and I'm not sure why. I would like to know which promise is failing. Passing a callback as a second parameter to the .then method does not help much, as I know that a promise is rejecting but not which promise is rejecting.

堆栈跟踪也没有帮助,因为第一项是 Promise.all()的错误处理程序。来自错误对象的行号传递给第二个函数的第一个参数传递给 try 函数的 Promise.all()只是我记录行号的行号。

A stack trace does not help either, as the first item is the Promise.all()'s error handler. A line number from the Error object passed to the first parameter of the second function passed to the try function of the Promise.all() is simply the line number of the line where I log the line number.

有谁知道找出哪个承诺拒绝的方法?

Does anybody know of a way to find out which promise is rejecting?

推荐答案

你可以使用 onreject 处理程序:

Promise.all(promises.map((promise, i) =>
    promise.catch(err => {
        err.index = i;
        throw err;
    });
)).then(results => {
    console.log("everything worked fine, I got ", results);
}, err => {
    console.error("promise No "+err.index+" failed with ", err);
});

通常,每个拒绝原因都应包含足够的信息来识别您需要处理的问题(或log)。

In general, every rejection reason should contain enough information to identify the issue that you need to handle (or log).

这篇关于Promise.all找到被拒绝的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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