1

I have the following code:

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;
}

When I call goodUsers I get the following output: TEST1 FILTERED TEST2 TEST3 TEST4

FILTERED should be last (obviously).

I tried various options but I seem to be not understanding something here. Do you guys notice what's going on?

stijn.aerts
  • 6,026
  • 5
  • 30
  • 46

1 Answers1

2

This's a correct behavior, async/await only affect the function where they are used. So you need to replace forEach which calls callback for each element, to for operator:

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']);
alexmac
  • 19,087
  • 7
  • 58
  • 69