Skip to content
Advertisement

How can I fetch an array of URLs with Promise.all?

If I have an array of urls:

JavaScript

And I want to build an object that looks like this:

JavaScript

I’ve been trying to learn to do this with fetch, which of course returns Promises.

Some things I’ve tried that don’t work:

JavaScript

This doesn’t look right, and in any case it doesn’t work — I don’t end up with an array [‘one’, ‘two’, ‘three’].

Is using Promise.all the right approach here?

Advertisement

Answer

Yes, Promise.all is the right approach, but you actually need it twice if you want to first fetch all urls and then get all texts from them (which again are promises for the body of the response). So you’d need to do

JavaScript

Your current code is not working because forEach returns nothing (neither an array nor a promise).

Of course you can simplify that and start with getting the body from each response right after the respective fetch promise fulfilled:

JavaScript

or the same thing with await:

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