如何使用承诺控制 setTimeout [英] How to control setTimeout with promises

查看:55
本文介绍了如何使用承诺控制 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();
}

这篇关于如何使用承诺控制 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆