Say I have a list of items like so:
const list = [0, 1, 2, 3, 4];
and I have some async fetch function:
async function fetchSomething(x) { /* ... */ }
I was wondering if there was a way to map the list
to the result of fetchSomething
but *have each fetch run after the next.
I know I can do this with async
and await
using for ... of
loops like so:
const list = [0, 1, 2, 3, 4];
function fetchSomething(x) {
return new Promise(resolve => {
setTimeout(() => {
const value = `fetched ${x}!`;
console.log(value);
resolve(value);
}, 500);
});
}
async function main() {
const newList = [];
for (const item in list) {
newList.push(await fetchSomething(item));
}
console.log({newList});
}
main();
but that isn't very "functional".
I also know I could use Promise.all
but the issue is that it fires off all the promises at once. I'd prefer if they went off sequentially:
const list = [0, 1, 2, 3, 4];
function fetchSomething(x) {
return new Promise(resolve => {
setTimeout(() => {
const value = `fetched ${x}!`;
console.log(value);
resolve(value);
}, 500);
});
}
async function main() {
const newList = await Promise.all(list.map(x => fetchSomething(x)));
console.log({newList});
}
main();
Any idea of how to map a list of items to promises and have each promise complete sequentially and still have it be "functional"/declarative style?