Every year a new version of javascript comes out. This year’s version, ES2020, released with a bunch of cool new features. While a lot of features got a lot of hype, a new method on the Promise primitive called allSettledseemed to slip under the radar — Despite the fact it’s great!

Let’s see when, why, and how you would use it.

Say we have a page that holds three inputs. One that updates a number, one that updates a username and one that updates a colour. When a user clicks Submit we will send three requests to the server (each to their respective endpoints) to update those values:

At the moment, if any of our requests fail we don’t do anything. Let’s add an error message to show to the user if one of the requests fail.

So we added some extra state to hold the error message and changed the onSubmit function to use a method called Promise.allIf any of the promises in Promise.all reject then it will call our catch handler with the first promise that rejected. The downside to this is that can only handle a single error. If more than one request fails, we will only show the errorMessage of the first promise that rejected; The other promises that rejected will be ignored and no errorMessage will be shown for it. That’s not good!

#javascript #react

Mastering Promise.allSettled in React
3.70 GEEK