M
M
Mulch2020-07-06 11:53:43
JavaScript
Mulch, 2020-07-06 11:53:43

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]


Where to dig?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-07-06
@Mulch

async function chain(arr) {
  const result = [];

  for (const item of arr) {
    result.push(await item(result[result.length - 1]));
  }

  return result;
}

Or
function chain(arr) {
  const result = [];

  return arr
    .reduce((prev, curr) => prev.then(curr).then(r => (result.push(r), r)), Promise.resolve())
    .then(() => result);
}

D
Dima Pautov, 2020-07-06
@bootd

Promise.all

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question