setTimeout、Promise、.then、async/await 区别

1. setTimeout

console.log('script start')      //1. 打印 script start
setTimeout(function () {
    console.log('settimeout')     // 4. 打印 settimeout
})                     // 2. 调用 setTimeout 函数,并定义其完成后执行的回调函数
console.log('script end')       // 3. 打印 script start

// 输出顺序:script start->script end->settimeout

setTimeout最后执行,判断到没有定时的时间点,到了就执行

2. Promise

Promise本身是同步的立即执行函数(如果一个任务已经完成,再添加回调函数,该回调函数会立即执行), 当在promise中执行resolve或者reject的时候, 此时是异步操作, 会先执行then/catch等,当主栈完成后,才会去调用resolve/reject中存放的方法执行,打印p的时候,是打印的返回结果,一个Promise实例。

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

3. then方法

const promise = new Promise((resolve, reject) => {
    console.log(1)
    resolve()
    console.log(2)
})

promise.then(() => {
    console.log(3)
})

console.log(4)

// 输出顺序: 1 -> 2 -> 4 -> 3

promise构造函数是同步执行的,then方法是异步执行的

Promise new的时候会立即执行里面的代码 then是微任务 会在本次任务执行完的时候执行 setTimeout是宏任务 会在下次任务执行的时候执行

4. async/await

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

console.log('script start');
async1();
console.log('script end')

// 输出顺序:script start->async1 start->async2->script end->async1 end

async 函数返回一个 Promise 对象,当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再执行函数体内后面的语句。可以理解为,是让出了线程,跳出了 async 函数体。 

await的含义为等待,async 函数需要等待await后的函数执行完成并且有了返回结果(Promise对象)之后,才能继续执行下面的代码。await通过返回一个Promise对象来实现同步的效果。 

 

异步笔试题总结:

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');
}, 0)
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

 

posted on 2019-11-21 14:05  活在当下zql  阅读(1017)  评论(0)    收藏  举报