Jake Jackson
Jake Jackson

Reputation: 1225

How to call a function after an asynchronous for-loop?

I have the following for-loop:

for await (const account of accountCursor) {
  const newAccount = handleAccount(account, migrationService);
  try {
    await migrationService.accountService.create(newAccount);
  } catch (error) {
    console.log('Unable to create account');
    throw Error(error)
  }
}

handleRelatedAccounts();  // call once the for-loop has completed

Once it has finished, I want to call another function. Since it is asynchronous, how can I call the function after the for-loop has finished, not during?

Upvotes: 1

Views: 43

Answers (2)

Thai Dang
Thai Dang

Reputation: 161

You do not have to do anything. handleRelatedAccounts(); always run after the loop. await means it will wait until the premise is finished to do the next code. Because you throw Error(error), it will stop the execution when there is an exception, handleRelatedAccounts(); will be never hit in this case.

Upvotes: 0

jsejcksn
jsejcksn

Reputation: 33691

Assuming you want to run the function whether or not an error is caught and re-thrown in your loop, you can just wrap the entire loop in a try...finally statement: below is an example. (If not, I'm not sure why you are re-throwing the caught error and what kind of behavior you expect.)

try {
  for await (const account of accountCursor) {
    const newAccount = handleAccount(account, migrationService);
    try {
      await migrationService.accountService.create(newAccount);
    } catch (error) {
      console.log('Unable to create account');
      throw Error(error)
    }
  }
}
finally {
  handleRelatedAccounts();  // call once the for-loop has completed
}

Upvotes: 1

Related Questions