异步执行步骤

2021-03-19  本文已影响0人  肥羊猪
async function async1() {
    console.log('async1 start');
    await async2();
    console.log('asnyc1 end');
}
async function async2() {
    console.log('async2');
}
console.log('script start');
setTimeout(() => {
    console.log('setTimeOut');
}, 0);
async1();
new Promise(function (reslove) {
    console.log('promise1');
    reslove();
}).then(function () {
    console.log('promise2');
})
console.log('script end');

输出结果:

script start
async1 start
async2
promise1
script end
asnyc1 end
promise2
setTimeOut

宏任务:setTimeout,setInterval
微任务:Promise.then(非new Promise),process.nextTick(node中)

事件的执行顺序,是先执行微任务,然后执行宏任务

new Promise同步的任务,会被放到主进程中去立即执行。而.then()函数是异步任务会放到异步队列中去
async关键字的函数会返回一个promise对象,如果里面没有await,执行起来等同于普通函数
await会让出线程,阻塞async内后续的代码,先去执行async外的代码

执行步骤.png
上一篇 下一篇

猜你喜欢

热点阅读