Answer the question
In order to leave comments, you need to log in
How to sequentially call asynchronous functions and write the result to an array?
Using async/await, you need to write a function that accepts an array of asynchronous functions and sequentially (the next one starts when the previous one has ended) calls them, passing the result of calling the previous function into the arguments.
Example:
const first = () =>
new Promise((resolve) => setTimeout(() => resolve(300)), 300);
const second= () =>
new Promise((resolve) => setTimeout(() => resolve(200)), 200);
const third = () =>
new Promise((resolve) => setTimeout(() => resolve(100)), 100);
promises([first, second, third]);
// Выполнит resolve(300) через 300 мс, потом resolve(200) через 200 мс, потом resolve(100) через 100 мс
// [300, 200, 100]
Answer the question
In order to leave comments, you need to log in
async function chain(arr) {
const result = [];
for (const item of arr) {
result.push(await item(result[result.length - 1]));
}
return result;
}
function chain(arr) {
const result = [];
return arr
.reduce((prev, curr) => prev.then(curr).then(r => (result.push(r), r)), Promise.resolve())
.then(() => result);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question