Can I catch exceptions from async methods without await?

Viewed 1603

How can I catch exceptions from doAsyncThing without throwing an await in? Each run of doAsyncThing is idempotent so I just want all of the operations to happen "at the same time" & then wrap up the process. I realized even if I put a try/catch inside the map, it won't actually catch it there because it's not in same thread at that point.

const promises  = entities.map(entity => {
  return entity.doAsyncThing();
});

await Promise.all(promises);
2 Answers

Can I catch exceptions from async methods without await?

No, not with try/catch. At the time your map callbacks finish, your async tasks have not even completed yet. promises contains an array of unsettled promises (assuming doAsyncThing is actually doing async work and does not directly return a resolved or rejected promise).

Depending on what exactly you want to do, you have several options.

  • Use catch within map to handle each thing individually:
const promises  = entities.map(entity => {
   return entity.doAsyncThing().catch(error => /* do something */);
});
await Promise.all(promises);
  • Use catch on Promise.all:
const promises  = entities.map(entity => {
   return entity.doAsyncThing();
});
Promise.all(promises).catch(error => /* do something */);
  • Use try/catch:
const promises  = entities.map(entity => {
   return entity.doAsyncThing();
});
try {
    await Promise.all(promises)
} catch (ex) {
    // do something
};

Depends on what are you trying to achieve. Same as your code but without await would be

const promises  = entities.map(entity => {
  return entity.doAsyncThing();
});

Promise.all(promises).catch(e => {
  // handle exception
});

But you need to understand that it will catch if ANY of your promises reject and resolve if ALL of your promises resolve.

If you want to handle every exception and get results of resolved promises you may need something like

const promises = entities.map(async entity => {
  try {
    return await entity.doAsyncThing();
  } catch (e) {
    // handle each exception
    return null;
  }
});

await Promise.all(promises);
Related