async并等待按顺序调用setTimeout对

时间:2018-03-31 11:07:32

标签: javascript async-await

如果我有setTimeout s这两个变量:

var printOne = setTimeout(function() {
  console.log("one!");
}, 500);

var printTwo = setTimeout(function() {
  console.log("two!");
}, 50);

仅举例来说。我想要的是,创建一个函数(asyncawait将调用上述变量,但是按顺序。就像这样:

theFunction(printOne, printTwo);
// Will output:
// one! 
// two!

2 个答案:

答案 0 :(得分:0)

要使用异步功能实现这一目标,您需要与promises一起工作。

另一种方法是将两个setTimeout调用包装到一个返回promise的函数中:

var printOne = function() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log("one!");
      resolve();
    }, 500);    
  })
}

var printTwo = function() {
  return new Promise(function(resolve) {
    setTimeout(function() {
      console.log("two!");
      resolve();
    }, 50);    
  })
}

function theFunction(one, two) {
}

async function main() {
  theFunction(await printOne(), await printTwo());
}

main();

答案 1 :(得分:0)

创建一个返回promise的函数,该函数封装setTimeout

var fnPromiseTimeout = async function(msg, time) { 
    return new Promise( (resolve) => setTimeout( () => {
      //console.log(msg);
      resolve(msg);
    }, time ) );
};

<强>演示

var fnPromiseTimeout = async function(msg, time) { 
    return new Promise( (resolve) => setTimeout( () => {
      //console.log(msg);
      resolve(msg);
    }, time ) );
};

async function f1(timer1, timer2)
{
  console.log("start");
  var a = await timer1;
  console.log(a);
  var b = await timer2;
  console.log(b);
  console.log("end");
}
f1(fnPromiseTimeout("one", 500), fnPromiseTimeout("two", 500));