Promise.all 和 Promise.race 是否有效地“处理"了所有承诺,这是一种记录在案的行为吗? [英] Is it a documented behavior that Promise.all and Promise.race effectively make all promises "handled"?

查看:31
本文介绍了Promise.all 和 Promise.race 是否有效地“处理"了所有承诺,这是一种记录在案的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面,代码 unhandledRejection 不会被 p2 触发,即使它也被拒绝,虽然晚于 p1:

In the following, code unhandledRejection doesn't get fired for p2, even though it also gets rejected, albeit later than p1:

process.on('unhandledRejection', (reason, promise) => 
  console.log(`unhandledRejection: ${reason}`));

async function delay(ms) {
  await new Promise(r => setTimeout(r, ms));
}

const p1 = async function f1(){
  await delay(100);
  throw new Error("f1");
}();

const p2 = async function f2(){
  await delay(200);
  throw new Error("f2");
}();

try {
  await Promise.race([p1, p2]);
  //await Promise.race([p1]);
}
catch (e) {
  console.error(e.message);
}

如果我像这样更改注释行:

If I change the commented line like this:

  //await Promise.race([p1, p2]);
  await Promise.race([p1]);

... 然后 unhandledRejection 确实像预期的那样为 p2 触发.对于 Promise.all() 观察到相同的行为.

... then unhandledRejection does get fired for p2, as expected. The same behavior is observed for Promise.all().

因此,Promise.racePromise.all 有效地防止了 unhandledRejection 事件的 Promise 没有赢得比赛但仍然获得拒绝了.这是记录在案的行为吗?我似乎在规范中找不到任何提及.

Thus, Promise.race and Promise.all effectively prevent the unhandledRejection event for promises which don't win the race but still get rejected. Is it a documented behavior? I can't seem to find any mentions of that in the specs.

推荐答案

是的,Promise.racePromise.all handle";您传递给它们的所有承诺的结果,无论该结果是否与 race/all 的承诺的结算有关.所以输"Promise.race 中的 promise 仍然被处理,即使来自 Promise.race 的 promise 只反映了获胜的 promise 发生了什么.类似地,如果 Promise.all 由于其输入承诺之一拒绝而拒绝,则稍后会处理来自其他输入承诺的任何拒绝,但不会对它们进行任何处理.

Yes, Promise.race and Promise.all "handle" the result of all of the promises you pass into them, regardless of whether that result was relevant to the settlement of the promise from race/all. So the "losing" promise in Promise.race is still handled, even though the promise from Promise.race only reflects what happened with the winning promise. Similarly, if Promise.all rejects because one of its input promises rejects, any rejections from other input promises later are handled but nothing is done with them.

您可以在规范中看到这一点,它将处理程序与传入的每个承诺的履行和拒绝挂钩,例如在 PerformPromiseRace:

You can see this in the specification where it hooks up handlers to both fulfillment and rejection of each promise passed in, for instance in Step 3.i of PerformPromiseRace:

执行?Invoke(nextPromise, then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).

Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).

这篇关于Promise.all 和 Promise.race 是否有效地“处理"了所有承诺,这是一种记录在案的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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