I want to return a chain of Promises into a single Promise. I want to know how acheive it.
function xbox(){
let games = "https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5"
let pages = []
let videogames = []
let play
for(let i = 1; i <= 5; i ){
let response = fetch(games `&page=${i}`)
pages.push(response)
let game = response.then(res => res.json()).then(data => data.results.map((e) => {
let allgames = {
ID: e.id
}
return allgames
}))
videogames = videogames.concat(game)
play = Promise.all(videogames.flat(1))
}
return play
}
Output
Basically my desired output would be a single Promise instead of showing a chain of 5 Promises with 20 results, a single Promise with 100 results.
I appreciate any help with my inquiry!
CodePudding user response:
Flatten the result after calling Promise.all
on the array of promises.
return play
.then(results => results.flat());
function xbox(){
let games = "https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5"
let pages = []
let videogames = []
let play
for(let i = 1; i <= 5; i ){
let response = fetch(games `&page=${i}`)
pages.push(response)
let game = response.then(res => res.json()).then(data => data.results.map((e) => {
let allgames = {
ID: e.id
}
return allgames
}))
videogames = videogames.concat(game)
play = Promise.all(videogames.flat(1))
}
return play
.then(results => results.flat());
}
xbox().then(console.log);
Cleaning your code up some more, it can be made to look like:
function xbox(){
const baseUrl = "https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5";
return Promise.all(Array.from(
{ length: 5 },
(_, i) => fetch(baseUrl '&page=' (i 1))
.then(res => res.json())
.then(data => data.results.map(({ id }) => ({ ID: id })))
))
.then(results => results.flat());
}
xbox().then(console.log);
CodePudding user response:
You can simply use promise all and club all the promises into single.
Issue with your code is you're trying to loop and in each iteration you're trying to put promise as Promise.all which doesn't makes sense as in each iteration you're getting one promise only.
So you need to loop and collect all promises and then place it in Promise.all
function xbox() {
let games = "https://api.rawg.io/api/games?key=f648fbbe7d024a9d9b021bbd24cea8b5"
return Promise.all(Array.from({
length: 5
}, (a, i) => i 1).map(v => {
return fetch(games `&page=${v}`).then(res => res.json()).then(data => data.results.map((e) => {
let allgames = {
ID: e.id
}
return allgames
}))
}))
}
xbox().then(d => console.log(d.flat(1)))