Search code examples
javascriptnode.jses6-promise

Can I catch exceptions from async methods without await?


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);

Solution

  • 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);