Home > Back-end >  How to call a function after an asynchronous for-loop?
How to call a function after an asynchronous for-loop?

Time:03-19

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?

CodePudding user response:

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
}

CodePudding user response:

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.

  • Related