0
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?

SPS
  • 147
  • 11
  • in the first instance, create functions that actually return promises... – Alnitak Sep 30 '20 at 13:39
  • @Alnitak: Could you please give some example for it? – SPS Sep 30 '20 at 13:44
  • This: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise – Randy Casburn Sep 30 '20 at 13:45
  • Does this answer your question? [Resolve promises one after another (i.e. in sequence)?](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence) – Maxwell s.c Sep 30 '20 at 17:28

2 Answers2

2

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();
}
Alnitak
  • 334,560
  • 70
  • 407
  • 495
-1

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))
])
Maxwell s.c
  • 1,583
  • 15
  • 29
  • this doesn't answer the question (which requires an _array_ of functions) – Alnitak Sep 30 '20 at 13:53
  • @Alnitak i've updated it, but you need to specify how exactly you want your functions to be stored or work to get a better answer – Maxwell s.c Sep 30 '20 at 13:54
  • It wasn't my question, but your use of `Promise.all` still doesn't resolve the fundamental question which was that the OP wants the functions to be called _in sequence_. – Alnitak Sep 30 '20 at 14:38
  • NB: this is why my answer uses a function that returns a function that in turn returns a Promise - your version instantiates all three Promises (and invokes the setTimeout calls) immediately. – Alnitak Sep 30 '20 at 15:00