But one doesn’t depend on the other, so we don’t have to wait for one to complete before we fire off the request for the next. And now if we imagi

Effective Promise Concurrency in JavaScript

submited by
Style Pass
2023-01-23 19:30:08

But one doesn’t depend on the other, so we don’t have to wait for one to complete before we fire off the request for the next.

And now if we imagine that each of those requests took 1 second to respond each, whereas in our original function we would wait for both in a row totaling 2 seconds for our function to complete, in this new function we wait for both concurrently so our function completes in 1 second — half the time!

But here is the kicker - if fetchProducts then errors afterward, this will not trigger the catch block. That is because our function has already continued. The catch code has run, the function has completed — we’ve moved on.

We will sadly only be made aware of the first error. The second error will be lost in the ether - with no user feedback, not being captured in our error logs - it’s effectively invisible (besides a little noise in the browser console).

In this case, if we get an error, we return handle the error and return it. So now our resulting user and product objects are either an Error, which we can check with instanceof, or otherwise our actual good result.

Leave a Comment