为什么 Promise.all 的错误?:TypeError:无法读取未定义的属性“Symbol(Symbol.iterator)”

Nic*_*ick 1 javascript node.js

我有以下控制器方法:

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
  );
}));
Run Code Online (Sandbox Code Playgroud)

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

UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“Symbol(Symbol.iterator)”

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

Ice*_*unk 7

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

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

const userPromises = users.map(user => sendAccountEmail(user.email, user.surname, org));
await Promise.all(userPromises);
Run Code Online (Sandbox Code Playgroud)