异步等待forEach不工作

时间:2017-08-18 14:12:09

标签: node.js asynchronous async-await koa

我有以下代码:

async function goodUsers(users) {
  const filteredUsers = [];

  users.forEach(async (userInstance) => {
    console.log('TEST1');

    const fromUserContacts = await db.userContactInvite.findAll({
      where: {
        fromUserId: userInstance.id,
      },
    });
    console.log('TEST2');
    await fromUserContacts.forEach((fromUserContact) => {
      console.log('TEST3');
      const userJson = fromUserContact.toJSON();
      userJson.contactState = 'INVITATION_SENT';
      filteredUsers.push(userJson);
    });

    console.log('TEST4');
  });

  console.log('FILTERED', filteredUsers);
  return filteredUsers;
}

当我打电话给goodUsers时,我得到以下输出: TEST1 FILTERED TEST2 TEST3 TEST4

FILTERED应该是最后一个(显然)。

我尝试了各种选项,但我似乎对此没有理解。你们注意到了发生了什么吗?

1 个答案:

答案 0 :(得分:2)

这是正确的行为,async/await仅影响使用它们的功能。因此,您需要将调用每个元素的回调的forEach替换为for运算符:



async function goodUsers(users) {
  const filteredUsers = [];

  for(user in users) {
    console.log('TEST1');
    const fromUserContacts = await new Promise(resolve => setTimeout(() => resolve(['c1', 'c2']), 500));

    console.log('TEST2');
    fromUserContacts.forEach(fromUserContact => {
      console.log('TEST3');
      filteredUsers.push('json');
    });

    console.log('TEST4');
  }

  console.log('FILTERED', filteredUsers);
  return filteredUsers;
}

goodUsers(['u1', 'u2']);