如何使用承诺控制 setTimeout

如何使用承诺控制 setTimeout

问题描述:

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

假设我有一个类似上面的函数数组(其中的函数数量未知).我想编写一个函数,将这个数组作为参数并按顺序执行它们.在上面的示例中,我希望它按顺序记录 1,2,3.既然 Promise.all 不保证执行顺序,那么可以不用回调地狱来实现吗?

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?

您无法从仅调用 setTimeout 的函数中获得承诺 - 它需要一些帮助,例如:

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);
  });
}

使用:

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

有了这个数组,你就可以依次await每个函数:

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

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