// promise 在ES6的语法中,Promise是sleep方法异步的实现一种方式,借助Promise方法可以优雅的构建sleep实现方法,避免了使用函数回调的使用方式。
let fun = () => console.log('time out');
let sleep2= (time)=> new Promise((resolve)=>{
setTimeout(resolve,time)
})
sleep2(2000).then(fun);
async await 使用
使用async await就可以避免Promise的一连串.then.then.then,
function sleep(duration) {
return new Promise(resolve => {
setTimeout(resolve, duration);
})
}
async function changeColor(color, duration) {
console.log('traffic-light ', color);
await sleep(duration);
}
async function main() {
await changeColor('red', 2000);
await changeColor('yellow', 1000);
await changeColor('green', 3000);
}
main();