首页 文章

承诺链接和所有

提问于
浏览
0

我已经构建了这个我不理解的用例 .

我想创建一个promises数组(示例中为var array )并添加解析数组中每个元素的所有promise . 可选地,对于阵列的某些元素,我想做一个额外的细化,所以我链接另一个 Promise (在 if (e === 'b') 内) .

我希望 Promise.all(array) 能够捕获拒绝条件,但它会打印:

> node .\test.js
b is ok
all clear
(node:1304) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: 'b is ok' is NOT ok

为什么会这样? Promise.all 不管理链接?

thePromise 指向另一个链接的承诺 . 我认为所有 thePromise 链都需要进行评估,以考虑它已解决,而不仅仅是第一个 . 我错过了什么吗?

我注意到实际的解决方案是重新分配这样的承诺:

thePromise = thePromise.then((msg) => ....

示例代码:

const array = [];
const arrayData = ['a', 'b', 'c'];

arrayData.forEach((e) => {
  let thePromise = newPromise(e);

  if (e === 'b') {
    thePromise.then((msg) => {
      console.log(msg);
      return newPromise(msg);
    });
  }

  array.push(thePromise);
});

Promise.all(array)
  .then(() => console.log('all clear'))
  .catch(err => console.log('something goes wrong', err));


function newPromise(value) {
  return new Promise((resolve, reject) => {
    if (value === 'b is ok') {
      reject(new Error(`'${value}' is NOT ok`));
    } else {
      resolve(`${value} is ok`);
    }
  });
}

谢谢你的解释

1 回答

  • 1

    Promise.all不管理链接?

    是的,它确实 . 它管理了 array 中的所有承诺,这些承诺都已实现,这就是为什么它记录了 all clear .

    Promise.all 不知道 - 无法知道 - 关于你用 thePromise.then(…) 创建的新承诺 . 它's not in the chain, it'分支了 . 当它被拒绝时,没有任何东西可以处理错误 .

相关问题