从经典面试题了解async、await、promise

evenloop
  1. 执行同步代码(属于宏任务,如遇微任务会推到微任务队列)
  2. 执行所有微任务
  3. 执行异步代码
面试题
async function async1() {
    console.log("async1 start");
    await async2();
    console.log("async1 end");
    return 'async return';
}

async function async2() {
    console.log("async2");
}

console.log("script start");

setTimeout(function() {
    console.log("setTimeout");
}, 0);

async1().then(function (message) { console.log(message) });

new Promise(function(resolve) {
    console.log("promise1");
    resolve();
}).then(function() {
    console.log("promise2");
});

console.log("script end");
解题
执行同步代码

script start

遇到setTimeout,推入宏任务队列
执行async1()

async1 start

遇到await 执行右侧表达式后让出线程,阻塞后面代码 *

async2

执行promise中的同步代码

promise1

将.then()推入微任务队列
向下执行同步代码

script end

同步代码执行完毕,执行所有微任务队列中的微任务

promise2

微任务执行完毕,执行await后面的代码

async1 end

带 async 关键字的函数,它使得你的函数的返回值必定是 promise 对象或undefined *

async return

带 async 关键字的函数,执行后会自动打印undefined *

undefined

开始下一轮evenloop,执行宏任务队列中的任务

setTimeout

扩展
带 async 关键字的函数,它使得你的函数的返回值必定是 promise 对象
async function fn1(){
    return 'async'
}

function fn2(){
    return 'unasync'
}

console.log(fn1())		// Promise {<resolved>: "async"}
console.log(fn2())		// unasync
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值