简体   繁体   中英

Using Promise.all to resolve fetch requests

I have an array of 4 request objects that I want to use the Fetch API on and get back promises. I then want to resolve each of these promises and get the values back.

Here is how I am building the request objects.

let requestsArray = urlArray.map((url) => {
        let request = new Request(url, {
            headers: new Headers({
                'Content-Type': 'text/json'
            }), 
            method: 'GET'
        });

        return request;
    });

And here is how I am trying to use Promise.all()

Promise.all(requestsArray.map((request) => {
        return fetch(request).then((response) => {
            return response.json();
        }).then((data) => {
            return data;
        });
    })).then((values) => {
        console.log(values);
    });

The last console.log(values) doesn't print anything to the console. Am I using Promise.all() wrong?

I know the first request goes through, and when I run each request individually, it works fine. The only issue is when I try to run them concurrently.

I can't see any problems, for me it returns just fine: https://jsfiddle.net/np5bx03j/ However, this is a test with jsfiddles /echo/json URLs and not your original ones. I therefore would assume some error occured in your case. I suggest adding a catch to log errors:

Promise.all(requestsArray.map((request) => {
    return fetch(request).then((response) => {
        return response.json();
    }).then((data) => {
        return data;
    });
})).then((values) => {
    console.log('values', values);
}).catch(console.error.bind(console));

EDIT: Just for the sake of completeness: I can't see any problems according to the API ( MDN ) or anything else either.

why map it twice? Let the request array return the actual promise from fetch.

let requestsArray = urlArray.map((url) => {
        let request = new Request(url, {
            headers: new Headers({
                'Content-Type': 'text/json'
            }), 
            method: 'GET'
        });

        return fetch(request).then(res => res.json());
    });

Now you have array of promises. Which Promise.all takes in.

Promise.all(requestsArray).then(allResults => {
  console.log(allResults)
})

Here's a jsfiddle that mocks this: https://jsfiddle.net/uu58t1jj/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM