Javascript将setTimeOut链接到Promise,以查找一个非常简单的示例

时间:2018-07-12 09:35:12

标签: javascript

对于防止地狱金字塔编程,我正在寻找使用“ Promise”的机会,但我还是不熟悉。

例如,我有这个丑陋的代码:

var timeA = 500;
var timeB = 800;
var timeC = 750;

window.setTimeout(function(){
    //do stuff 1
    window.setTimeout(function(){
    //do stuff 2
        window.setTimeout(function(){
        //do stuff 3
        }, timeA);
    }, timeB);
}, timeC);

如何使用Promise机制更改代码? 谢谢:)

3 个答案:

答案 0 :(得分:2)

您需要将setTimeout包装到Promise中。

下面,我还展示了如何与async / await一起使用。.

var timeA = 500;
var timeB = 800;
var timeC = 750;

function wait(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

/*wait(timeA).
  then(() => console.log("timeA")).
  then(() => wait(timeB)).
  then(() => console.log("timeB")).
  then(() => wait(timeC)).
  then(() => console.log("timeC")); */

async function run() {
  await wait(timeA);
  console.log("timeA")
  await wait(timeB);
  console.log("timeB")
  await wait(timeC);
  console.log("timeC");
}

run();

答案 1 :(得分:1)

您可以通过以下方式创建“ promisifying”功能:

function doLater(thunk, delay){
    return new Promise(function(resolve, reject){
        window.setTimeout(function() {
            resolve(thunk());
        }, delay);
    });
}

然后您可以这样称呼:

doLater(doSomething, delay1)
    .then(result => doLater(doSomethingElse, delay2)
    .then(result => doLater(doAnotherThing(result), delay3)

答案 2 :(得分:1)

例如:

var timeA = 500;
var timeB = 800;
var timeC = 750;
var wait = (seconds) => new Promise(r => setTimeout(r, seconds));

wait(timeA)
  .then(() => console.log('A'))
  .then(() => wait(timeB))
  .then(() => console.log('B'))
  .then(() => wait(timeC))
  .then(() => console.log('C'));

但是,当您处理异步问题时,使用setTimeout几乎总是不可行。