Search code examples
javascriptes6-promise

Inspecting Errors after calling Promise.allSettled


In my code I'm trying to dispatch jobs (FoundryVTT data object migrations) in parallel, and capture any errors on the way.

After they have all run their course, I'm trying to print the error details together. The problem is the errors for an individual actor are not "caught", but I can see the rejected promises at the end. Here's my code:

const actorMigrations = await game.actors.contents.map((actor) => {
  try {
    return this.updateActor(actor);
  } catch (err) {
    throw new Error(`${actor.name} had a migration error: ${err.message}`);    
  }
});
const values = await Promise.allSettled(actorMigrations);
for (const value of values.filter((v) => v.status !== "fulfilled")) {
  LOGGER.error(`Migration error: ${value.reason.message}`);
  LOGGER.error(value.reason.stack);
  return false;
} 

What's the right pattern I should be following here?


Solution

  • I suppose you're looking for

    const actorMigrations =   game.actors.contents.map((actor) => {
    //                      ^
      try {
        return await this.updateActor(actor);
    //         ^^^^^
      } catch (err) {
        throw new Error(`${actor.name} had a migration error: ${err.message}`);    
      }
    });
    

    You don't need to await the array that map() returns (it won't do anything - you can only await the promise that Promise.allSettled() returns), and you'll want to await the promise that updateActor() returns so that rejections will be caught by the try/catch block.