Reputation: 1844
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.
Upvotes: 3
Views: 19788
Reputation: 4057
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/
Upvotes: 4
Reputation: 6517
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.
Upvotes: 7