1

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?

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

From one Jackson to another (I'm assuming that's what jcksn is supposed to mean), thank you. I completely forgot about finally{}.
@JakeJackson It does :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.