How to execute one at a time items from a sequence array using Promise - Javascript

Asked

Viewed 89 times

0

I have an array where I want to execute each item, but one can only start after finishing the previous one. The example below is printing in sequence 2000,5000,10000 which makes me understand that the three items were executed simultaneously. I would like each item to start only after the completion of the previous one. I was hoping it would be printed 10000,5000,2000.

const durations = [10000, 5000, 2000]

const timeOut = (t) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(t)
            resolve(true)
        }, t)
    })
}

for (let index = 0; index < durations.length; index++) {
    const element = durations[index];
    timeOut(element);
}

1 answer

2


You can expect the return of each trial. I did it as follows, using the async and await, so the loop in the array will await the return of your file for each item.

const durations = [10000, 5000, 2000]

const timeOut = (t) => {
  return new Promise(resolve => setTimeout(resolve, t));
}

const init = async () => {
  for(i = 0; i < durations.length; i++) {
    const element = durations[i];
    await timeOut(element);
    console.log(element);
  }
}

init();

The problem with yours is that for is not awaiting the return of their promise, this way it will execute all the elements at once.

Another simplified way to write your code

const durations = [10000, 5000, 2000]

const timeOut = (t) => new Promise(resolve => setTimeout(resolve, t));

const init = async () => {
  for(const element of durations) {
    await timeOut(element);
    console.log(element);
  }
}

init();

  • 1

    Thanks!! His reply helped me a lot to solve the API call I was making, and all were being done in parallel, without respecting the array sequence. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.