【问题标题】:Why the error for Promise.all?: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined为什么 Promise.all 的错误?:TypeError:无法读取未定义的属性 'Symbol(Symbol.iterator)'
【发布时间】:2019-12-18 18:15:16
【问题描述】:

我有以下控制器方法:

const org = await organisation.toJSON().name;
// The next line works fine, that's not the problem
const users = await organisation.getUsers(organisation.toJSON().id, User);
await Promise.all(users.forEach(async user => {
  await sendAccountEmail(
    user.email,
    user.surname,
    org
  );
}));

对于Promise 行,我收到一个错误:

UnhandledPromiseRejectionWarning:TypeError:无法读取属性 'Symbol(Symbol.iterator)' of undefined

知道我的代码有什么问题吗?

【问题讨论】:

  • Array.prototype.forEach 不返回任何内容。
  • @ASDFGerte 只是为了弄清楚为什么这是相关的 - 如果它没有返回任何内容,它实际上会返回 undefined。你把undefinedPromise.all
  • 这是否意味着我不应该在这里使用 Promise 来遍历用户?
  • 这意味着您应该将所有承诺放入一个数组中并将 that 提供给Promise.all。你现在所拥有的既不是这里也不是那里 - 你循环一些数据,提出一些请求,然后尝试await,但使用Promise.all等待一切,但从不给它任何东西等待。看看here

标签: javascript node.js


【解决方案1】:

您错误地使用了Promise.all。该方法希望您给它一个充满 Promises 的数组(或另一个可迭代对象),然后它等待直到该数组中的所有 Promises 都已解决(解决或拒绝)。您不应该迭代参数内的数组,特别是不使用返回未定义的forEach,从而使您的代码等效于await Promise.all(undefined)——所以您现在可以看到为什么会出错,不是吗?

您应该做的是使用 Array.map 将您的用户数组转换为您要等待的 Promise 数组:

const userPromises = users.map(user => sendAccountEmail(user.email, user.surname, org));
await Promise.all(userPromises);

【讨论】:

    【解决方案2】:

    虽然您已经有了答案,但我想我会解释您遇到的实际错误,因为了解此特定错误的含义以及了解 Promise.all() 的实际工作原理很有用。

    你得到的错误是这样的:

    UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined

    这里有两件不同的事情。

    1. Promise.all() 期望一个可迭代对象作为其参数,它可以从中获取一个迭代器并迭代其中的项目。您的代码正在传递.forEach() 的结果,即undefined,因此此错误的第一部分是undefined 不是可迭代的,并且发现它的方式是它没有属性Symbol(Symbol.iterator) .

    2. 此错误的第二部分是UnhandlePromiseRejectionWarning。这表明 await Promise.all(...) 拒绝并且您没有对此进行错误处理。您应该在await 周围有一个try/catch,或者使用.catch(),如Promise.all().catch()。您接受的答案并未解决此编码问题。虽然修复您的代码会阻止在您的代码的正常执行中发生拒绝,但sendAccountEmail() 在我看来就像一个可能会遇到故障并可能拒绝的函数。您的代码需要处理这种情况。我们不能在这里真正建议最佳的整体错误处理策略,因为我们需要查看代码的更大上下文才能知道发生错误时应该发生什么。但是,您需要处理所有可能的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2017-11-03
      • 1970-01-01
      • 2019-04-29
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多