前端开发那些事儿

setTimeout、Promise、Async/Await 的

2021-02-19  本文已影响0人  vivianXIa

setTimeout

Promise

本身是同步的立即执行函数,会先执行then catch,当主栈完成后,才会调用resolve/reject

console.log('script start')
let promise1 = new Promise(function (resolve) {
    console.log('promise1')
    resolve()
    console.log('promise1 end')
}).then(function () {
    console.log('promise2')
})
setTimeout(function(){
    console.log('settimeout')
})
console.log('script end')
// 输出顺序: script start->promise1->promise1 end->script end->promise2->settimeout
func1().then(res => {
    console.log(res);  // 30
})

由于因为async await 本身就是promise+generator的语法糖。所以await后面的代码是microtask。所以

async function async1() {
    console.log('async1 start');
    await async2();
    console.log('async1 end');
}

等价于

async function async1() {
    console.log('async1 start');
    Promise.resolve(async2()).then(() => {
                console.log('async1 end');
        })
}
PS 面试题
// 今日头条面试题
async function async1() {
    console.log('async1 start')
    await async2()
    console.log('async1 end')
}
async function async2() {
    console.log('async2')
}
console.log('script start')
setTimeout(function () {
    console.log('settimeout')
})
async1()
new Promise(function (resolve) {
    console.log('promise1')
    resolve()
}).then(function () {
    console.log('promise2')
})
console.log('script end')
//答案:
script start
async1 start
async2
promise1
script end
async1 end
promise2
settimeout
上一篇 下一篇

猜你喜欢

热点阅读