How to I consume the Promise.all fetch api json data? It works fine to pull it if I don\'t use Promise.all. With .all it actually returns the values of the query in the cons
Using Promise.all
to fetch the json responses of each of the API's-
CODE:
Promise.all([
API_1_Promise,
API_2_Promise,
API_3_Promise])
.then(allResults => console.log(allResults))
.catch(err => console.log(err))
In which API_1_Promise,API_2_Promise,API_3_Promise
is defined as
API_1_Promise = fetch(`API_URL_1`, { *Add required headers* }).then(response => response.json())
API_2_Promise = fetch(`API_URL_2`, { *Add required headers* }).then(response => response.json())
API_3_Promise = fetch(`API_URL_3`, { *Add required headers* }).then(response => response.json())
RESPONSE: This will print the array of responses from all the API calls In console-->
[JSON_RESPONSE_API1, JSON_RESPONSE_API2, JSON_RESPONSE_API3]
You can just throw await
in front of your Promise instead of awaiting each individual fetch
await Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]).then(async([aa, bb]) => {
const a = aa.json();
const b = bb.json();
return [a, b]
})
.then((responseText) => {
console.log(responseText);
}).catch((err) => {
console.log(err);
});
Hope this helps
Simplest solution is to repeat use of Promise.all, to wait for all .json() to resolve. Just use
Promise.all([fetch1, ... fetchX])
.then(result => Promise.all(result.map(v => v.json()))
.then(result => {... result[0, ...X] available as objects})
Aparently aa.json()
and bb.json()
are returned before being resolved, adding async/await
to that will solve the problem :
.then(async([aa, bb]) => {
const a = await aa.json();
const b = await bb.json();
return [a, b]
})
Promise.all([
fetch('https://jsonplaceholder.typicode.com/todos/1'),
fetch('https://jsonplaceholder.typicode.com/todos/2')
]).then(async([aa, bb]) => {
const a = await aa.json();
const b = await bb.json();
return [a, b]
})
.then((responseText) => {
console.log(responseText);
}).catch((err) => {
console.log(err);
});
Still looking for a better explaination though
Instead of return [aa.json(),bb.json()]
use return Promise.resolve([aa.json(),bb.json()])
. See documentation on Promise.resolve()
.