The sequence in which the array should be displayed is getting disrupted
const arr = [1, 2, 3, 4, 5, 6];
const fooFunc = async (num) => {
if (num % 2 === 0) {
const data = await fetch(`https://jsonplaceholder.typicode.com/todos/${num}`);
const obj = await data.json();
return obj;
}
return {
name: 'test OBJ',
des: 'just to see how will it display',
num: num
}
}
const arrNew = async () => {
await Promise.all(arr.map(async (item) => {
const newObj = await fooFunc(item);
console.log(newObj, item);
return item * 2;
}))
}
arrNew();
I know this is because only some of the items are having a promise, but is there some way we can get that in proper sequence.
Js fiddle link: https://jsfiddle.net/Lu0f3psa/2/
you can try like this
const arr = [1, 2, 3, 4, 5, 6];
const fooFunc = async (num) => {
if (num % 2 === 0) {
const data = await consumeAPI(num);
const obj = data.json();
return obj;
}
return {
name: 'test OBJ',
des: 'just to see how will it display',
num: num
}
}
const arrNew = async () => {
await Promise.all(arr.map(item => {
const newObj = await fooFunc(item);
console.log(newObj, item);
return item * 2;
}))
}
const consumeAPI = (num) => {
// here we resolve the promise after api consumed
return new Promise(resolve => {
fetch(`https://jsonplaceholder.typicode.com/todos/${num}`).then(response => {
resolve(response);
});
})
}
arrNew();