在nodejs8.0+的版本中,已经支持 await, async 异步关键字了,实现“异步延迟”就简单多了
封装代码
common.js
class Ut {
/**
* 异步延迟
* @param {number} time 延迟的时间,单位毫秒
*/
static sleep(time = 0) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time);
})
};
}
module.exports = Ut;
使用例子
test.js
let Ut = require("./common");
(async () => {
console.log("开始");
let t1 = +new Date();
console.time("总延迟");
console.time("第一次延迟");
await Ut.sleep(2000);
console.timeEnd("第一次延迟");
console.time("第二次延迟");
await Ut.sleep(4000);
console.timeEnd("第二次延迟");
console.timeEnd("总延迟");
let t2 = +new Date();
console.log(t2 - t1);
})()
运行结果

摘自: