settimeout,async,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
我们来挨个分析一下,
await async2();//执行这一句后,输出async2后,await会让出当前线程,将后面的代码加到任务队列中,然后继续执行test()函数后面的同步代码
执行到setTimeout函数时,将其回调函数加入队列(此队列与promise队列不是同一个队列,执行的优先级低于promise)。继续执行
创建promise对象里面的代码属于同步代码,promise的异步性体现在then与catch处,所以promise1被输出,然后将then函数的代码加入队列,继续执行同步代码,输出script end。
至此同步代码执行完毕,开始从队列中调取任务执行,由于刚刚提到过,setTimeout的任务队列优先级低于promise队列,所以首先执行promise队列的第一个任务,即执行async1中await后面的代码,输出async1 end。
然后执行then方法的部分,输出promise2。最后promise队列中任务执行完毕,再执行setTimeout的任务队列,输出settimeout。
至此,该题的输出结果分析完毕了,这类的执行结果可以用一句话总结,先执行同步代码,遇到异步代码就先加入队列,然后按入队的顺序执行异步代码,最后执行setTimeout队列的代码。
补充一下队列任务优先级:promise.Trick()>promise的回调>setTimeout>setImmediate
settimeout,async,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
我们来挨个分析一下,
await async2();//执行这一句后,输出async2后,await会让出当前线程,将后面的代码加到任务队列中,然后继续执行test()函数后面的同步代码
执行到setTimeout函数时,将其回调函数加入队列(此队列与promise队列不是同一个队列,执行的优先级低于promise)。继续执行
创建promise对象里面的代码属于同步代码,promise的异步性体现在then与catch处,所以promise1被输出,然后将then函数的代码加入队列,继续执行同步代码,输出script end。
至此同步代码执行完毕,开始从队列中调取任务执行,由于刚刚提到过,setTimeout的任务队列优先级低于promise队列,所以首先执行promise队列的第一个任务,即执行async1中await后面的代码,输出async1 end。
然后执行then方法的部分,输出promise2。最后promise队列中任务执行完毕,再执行setTimeout的任务队列,输出settimeout。
至此,该题的输出结果分析完毕了,这类的执行结果可以用一句话总结,先执行同步代码,遇到异步代码就先加入队列,然后按入队的顺序执行异步代码,最后执行setTimeout队列的代码。
补充一下队列任务优先级:promise.Trick()>promise的回调>setTimeout>setImmediate