0

The following code sets the row.already_messaged_clients absolutely fine and is accessible outside of the loop.

businesses.forEach(async function(row) {
// let already_messaged_clients_arr = await getAlreadyMessagedClientsForPlaceID(row.place_id);
row.already_messaged_clients = 3;
});

When I use an await like this:

businesses.forEach(async function(row) {
let already_messaged_clients_arr = await getAlreadyMessagedClientsForPlaceID(row.place_id);
row.already_messaged_clients = 3;
});

row.already_messaged_clients does not get set. Why is this?

Thanks for your help

TMO
  • 65
  • 8
  • 1
    `await` does what it says and *waits* for `getAlreadyMessagedClientsForPlaceID` to finish before continuing. Which, in turn, means that every statement after the `await` also has to wait. – VLAZ Apr 18 '23 at 11:44
  • Does getAlreadyMessagedClientsForPlaceID actually resolve at some point? Until it resolves the function execution will be suspended and the property wont get set – Egge Apr 18 '23 at 11:47
  • Yes it resolves, I can print out the result of getAlreadyMessagedClientsForPlaceID – TMO Apr 18 '23 at 11:47
  • Suhel Khan's answer works, why does it work with a normal loop but not a foreach? – TMO Apr 18 '23 at 11:49

1 Answers1

1

you can use a 'for...of' loop instead of 'forEach'

for (let row of businesses) {
  let already_messaged_clients_arr = await 
  getAlreadyMessagedClientsForPlaceID(row.place_id);
  row.already_messaged_clients = 3;
}
Suhel Khan
  • 34
  • 4
  • This works, thanks! Why does it work with a normal loop but not a foreach? – TMO Apr 18 '23 at 11:49
  • because the normal loop is synchronous while the forEach loop is asynchronous. – Suhel Khan Apr 18 '23 at 11:50
  • 1
    @SuhelKhan erm, no. `.forEach` is synchronous but if it executes async functions, they'll still finish later. `for..of` is not "synchronous" given that it works with async code. It just works in the same mode as the rest of the function. – VLAZ Apr 18 '23 at 11:53