大脑暴来了~~易头晕者勿入
题目一:
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
const newPromise6 = new Promise(function(resolve, reject) {
resolve(console.log('promise1'));
});
newPromise6.then(function() {
console.log('promise2');
}).then(function() {
console.log('promise3');
});
console.log('script end');在chrome中输出结果?
结果:
script start
promise1
script end
promise2
promise3
setTimeout
解析:
异步任务之间,会存在差异,所以它们执行的优先级也会有区别。
大致分为 微任务(microtask,如:Promise、MutaionObserver等)和
宏任务(macrotask,如:setTimeout、setInterval、I/O等)。
1、setTimeout 定时器,属于js任务队列里的宏任务。
指的是把任务队列塞进执行栈里等待执行线程依次执行。虽然可以把它设置微0,但是仍然需要等待本轮执行环境里面的所有同步和异步任
执行完毕之后才会去执行它。
2、promise es6的异步语法,属于js任务队列里的微任务。
在执行本轮宏任务的过程中,如果遇到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) {
resolve(console.log("promise1"));
}).then(function () {
console.log("promise2");
});
console.log('script end');
答案:
script start
async1 start
async2
promise1
script end
async1 end
promise2
settimeout
题目三:将promise调入前面,比较一下then和await
new Promise(function (resolve) {
resolve(console.log("promise1"));
}).then(function () {
console.log("promise2");
});
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();
console.log('script end');
答案:
script start
async1 start
async2
promise1
script end
promise2
async1 end
settimeout
解析:
3、async await 异步语法,基于promise,是其语法糖,让异步更像同步任务。
如果使用async,函数体里有return XX,会被包装成一个异步promise.resolve('XXX'), 如果没有显式return,那么async也同样包装成promise.resolve('undefined');
注意:await 标志着js会去先执行一遍后面紧跟的函数,然后马上让出线程,跳出整个async
,去执行本轮执行周期里面的任务,等待本轮的宏任务(同步任务)执行完成之后,再回来async里等待之前await的函数的返回值,如果是返回值异步promise,那么会把它塞入promise.resolve()微任务(异步任务执行栈),等待它前面的异步任务执行完毕之后,再得到await promise.resolve()的值,然后才是去执行await后面的逻辑,如果await 函数体返回的不是异步promise,那么就直接去执行其后面的逻辑。
😊终极大boss
async function async1() {
console.log("async1 start");
await async2();
const newPromise6 = new Promise(function(resolve, reject) {
resolve(console.log('promise11111'));
}).then(() => {console.log('then2222222')});
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) {
resolve(console.log("promise1"));
}).then(function () {
console.log("promise2");
});
console.log('script end');
答案:
script start
async1 start
async2
promise1
script end
promise11111
async1 end
promise2
then2222222
settimeout
自己动手敲一敲,理解一下下吧~