【问题标题】:Why do I get unhandled promise rejection in this situation?为什么在这种情况下我会收到未处理的承诺拒绝?
【发布时间】:2020-01-15 06:04:14
【问题描述】:

我的代码中有下一个函数可能会因以下几个原因而中断执行:

const getAndCheckItem = async (itemId) => {
    try {
        const item = await getItem(itemId);
        if(item.firstFail) {
            throw "First fail";
        }
        if(item.secondFail) {
            throw "Second fail";
        }
        if(notGood(item)) {
            throw "Third fail"; 
        }

        return item;
    }
    catch(err) {
        return Promise.reject(err);
    }
};

如果我按以下方式在其他异步函数中调用它,一切都很好,并且任何内部抛出都会被处理:

try {
    item = await getAndCheckItem(ids[0]);
}
catch(err) {
    // handle error
}

但是,当我为多个 id 调用函数时:

try {
    items = await Promise.all([ids.map(value => getAndCheckItem(value))]);
}
catch(err) {
    // handle error
}

如果发生任何内部抛出,我会收到未处理的承诺拒绝。我了解 Promise.all() 将任何返回的非承诺值视为已解决的承诺。但是,Promise.reject(err) 应该返回一个 Promise 并因此得到处理。有什么问题?

【问题讨论】:

  • 尝试删除ids.map 上的方括号。 map() 已经返回一个数组
  • @CristopherNamchee 谢谢您,先生!我花了几个小时来定位错误,阅读文章并改变我对宇宙的理解,但像往常一样,看错了地方。 :)

标签: javascript node.js asynchronous promise async-await


【解决方案1】:

Promise.all() 将任何返回的非承诺值视为已解决的承诺。

当然,但是当你这样做时

return Promise.reject(err);

你正在返回一个 Promise,所以一旦它被调用者解包,getAndCheckItem 调用就会导致 Promise 被拒绝。执行return Promise.reject(err) 与在async 内部执行throw err 非常相似。

如果你在 catch 中所做的只是重新抛出或返回一个被拒绝的 Promise,那么它没有多大意义 - 你可以完全放弃这部分,让调用者处理它:

const getAndCheckItem = async (itemId) => {
  const item = await getItem(itemId);
  if(item.firstFail) {
    throw "First fail";
  }
  if(item.secondFail) {
    throw "Second fail";
  }
  if(notGood(item)) {
    throw "Third fail"; 
  }
  return item;
}

您当前还向Promise.all 传递了一个 数组数组 的 Promises:

await Promise.all([ids.map(value => getAndCheckItem(value))]);

在这种情况下,Promise.all 不会真正做任何事情,因为它的数组中唯一的一项是非 Promise(另一个数组)。如果任何 inner 承诺拒绝,它们将不会被处理,因此您将得到未处理的拒绝。

相反,将一组 Promises 传递给 Promise.all

await Promise.all(ids.map(value => getAndCheckItem(value)));

或者,更简洁:

await Promise.all(ids.map(getAndCheckItem));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多