Skip to content
Advertisement

Capture request response code of rejected promises with Promise.allSettled

I’m using Promise.allSettled to call an array of URLs and I need to capture the response code of the request(s) of the rejected promise(s). Using the value of result.reason provided by Promise.allSettled is not accurate enough to assess the reason of rejection of the promise. I need the request response code (400, 500, 429, etc.).

I have so far the below:

JavaScript

How could I capture the response code of the request of the rejected promise and add it as a property within the returned array? The returned array should look ideally like this:

JavaScript

Any ideas?

Advertisement

Answer

fetch doesn’t reject its promise on HTTP failure, only network failure. (An API footgun in my view, which I wrote up a few years back on my anemic old blog.) I usually address this by wrapping fetch in something that does reject on HTTP failure. You could do that as well, and make the failure status available on the rejection reason. (But you don’t have to, see further below.)

JavaScript

Then you could pass an async function into map to handle errors locally, and use Promise.all (just because doing it all in one place is simpler than doing it in two places with Promise.allSettled):

JavaScript

Or you can do it without a fetch wrapper:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement