How to return the Promise.all fetch api json data?
I came across the same problem and my goal was to make the Promise.all()
return an array of JSON objects
.
let jsonArray = await Promise.all(requests.map(url => fetch(url)))
.then(async (res) => {
return Promise.all(
res.map(async (data) => await data.json())
)
})
And if you need it very short (one liner for the copy paste people :)
const requests = ['myapi.com/list','myapi.com/trending']
const x = await Promise.all(requests.map(url=>fetch(url))).then(async(res)=>Promise.all(res.map(async(data)=>await data.json())))
Instead of return [aa.json(),bb.json()]
use return Promise.resolve([aa.json(),bb.json()])
. See documentation on Promise.resolve()
.
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
The simplest solution would be to repeat the use of Promise.all
, to just wait for all .json()
to resolve.
Just use :
Promise.all([fetch1, ... fetchX])
.then(results => Promise.all(results.map(r => r.json())) )
.then(results => { You have results[0, ..., X] available as objects })