Search code examples
javascriptes6-promise

How does promise.all handle multiple API calls when one of them fails?


I had a question on how promise.all handles rejection.

Let's say we have the following command

await Promise.all([
  server1.logMessage(),
  server2.logMessage()
])

And let's say server1 takes 2secs to log and server2 takes 5secs to log.

And what happens if the server1.logMessage() returns a error in 1 sec. Can we be sure that server2 will at least log the message even though the resultant promise from promise.all is rejected?

Or do i need to use Promise.allSettled?


Solution

  • Yes, your promises look to be independent. Your code is equivalent to this:

    const prom1 = server1.logMessage();
    const prom2 = server2.logMessage();
    await Promise.all([prom1, prom2])
    

    All the Promise.all does is adjust the flow of the program in that block - it doesn't affect what either logMessage may or may not do. If one logMessage happens to log a message, or if it happens to error instead, that'll have no effect on what the other logMessage does.