JS异步事件顺序:setTimeout,async,promise

为什么最近更新那么频繁,还不是因为笔试的时候瞎了?

先说异步事件执行顺序的规则:

1. 定时器异步队列和promise队列不是同一队列,promise优先级高于setTimeout;

2. 创建promise对象里面的代码属于同步代码,其异步性体现在then和catch处;

3. 遇到await,先执行完await所在行的事件(阻塞到执行完成),然后让出当前线程,继续走同步事件,await后面的语句等同于Promise.resolve(),进入promise的异步队列排队。

好了,理解这些就能做题了

async function async1() {
    console.log("async1 start");      //2  同步事件
    await  async2();                  //3  执行完后继续走同步事件
    console.log("async1 end");        //6  await之后的代码 首选进入promise异步队列
}
async  function async2() {
    console.log( 'async2');           //3
}
console.log(
"script start"); // 1 同步事件! setTimeout(function () { console.log("settimeout"); //8 最后,定时器的异步走最后!!! },0); async1(); //2 走异步函数内部的同步事件 new Promise(function (resolve) { console.log("promise1"); //4 同步事件! resolve(); }).then(function () { console.log("promise2"); //7 最后进入promise异步队列 }); console.log('script end'); //5 同步事件!

加了备注了,但还是上结果吧

 

注意:await只能存在与 async 定义的函数内部, 遇到await 之后,代码就暂停执行了,必须等await代码执行完成后,才能进入下一步,下一步仍是先走同步代码。 

懂了么?如果对 async 还迷糊,那就做以下测试!

上代码认识一下async

async function timeout() {
    console.log('hello world');     //类似于创建promise对象时的同步代码
    return '我属于promise对象'       //这才是promise对象返回的resolve对象
}
timeout().then((result)=>{
    console.log(result)
})
console.log('虽然在后面,但是我先执行');     //同步事件

输出结果:

 

 所以:async所定义的异步函数,其返回值是promise对象 

async function timeout(flag) {
    if (flag) {
        return 'hello world'
    } else {
        return 'my god, failure'
    }
}
console.log(timeout(true))  // 调用Promise.resolve() 返回promise 对象。
console.log(timeout(false)); // 调用Promise.reject() 返回promise 对象。

 

posted @ 2019-09-18 17:32  牛龙飞  阅读(1750)  评论(0编辑  收藏  举报