SPS
SPS

Reputation: 157

How to control setTimeout with promises

var functionsArray = [
  function() {
        setTimeout(function() {
        console.log(1);
    }, 100);
  },
  function() {
    setTimeout(function() {
        console.log(2);
    }, 200);
  },
    function() {
        setTimeout(function() {
            console.log(3);
    }, 10);
  }
],

Say I have an array of functions like above(the number of functions in it is not known). I want to write a function which takes this array as parameter and executes them in sequence. In the example above, I want it to log 1,2,3 in the sequence. Since Promise.all does not guarantee the order of execution, is it possible to achieve this without callback hell?

Upvotes: 0

Views: 173

Answers (2)

Alnitak
Alnitak

Reputation: 339776

You can't get a promise from a function that just calls setTimeout - it needs some help, e.g.:

function after(n, f) {
  return () => new Promise(resolve => {
    setTimeout(() => {
        resolve(f());
    }, n);
  });
}

with usage:

var functionsArray = [
  after(100, () => console.log(1)),
  after(200, () => console.log(2)),
  after( 10, () => console.log(3)),
];

With that array you can then just await each function in turn:

for (let f of functionsArray) {
  await f();
}

Upvotes: 2

Maxwell s.c
Maxwell s.c

Reputation: 1668

You can write an simple setTimeoutPromise function:

function timeoutPromise(time = 0){
  return new Promise(resolve => setTimeout(resolve, time)
} 


await timeoutPromise(10);
console.log('waited 10 sec')
timeoutPromise(20).then(() => console.log('waited 20 sec')

//make a new array as you like

Promise.all([
 timeoutPromise(100).then(() => console.log(1)),
 timeoutPromise(200).then(() => console.log(2)),
 timeoutPromise(300).then(() => console.log(3))
])

Upvotes: -1

Related Questions