js单线程
要想知道js的同步任务与异步任务(宏任务与为微任务)的执行顺序,首先要搞清楚什么是宏任务和微任务,js是一种单线程语言,但是当任务过多就会出现拥挤,线程中就出现了同步任务和异步任务,异步任务分为宏任务和微任务。
同步任务
同步任务没有优先级之分谁在代码的前面就先执行谁,且同步任务会进行等待,前一个任务执行完毕才进入下一个任务。
异步任务
异步任务分为宏任务和微任务,微任务会先于宏任务执行,
常见的宏任务: script脚本、setTimeout、setInterval之类的定时事件,UI渲染
常见的微任务: process.nextTick()、promise.then()(new Promise不算!)、Object.observe()
代码输出题一
console.log('1');
async function first() {
console.log('first函数');
}
setTimeout(() => {
console.log('settimeout 2');
}, 0);
Promise.resolve().then(() => {
console.log('promise 3');
});
new Promise((resolve, reject) => {
console.log(4);
resolve();
}).then((res) => {
console.log(5);
});
first();
console.log('6');
正确答案:
解释过程:
// 整体script作为第一个宏任务进入主线程......0
// 同步任务console.log直接执行
console.log('1'); ......1
async function first() {
console.log('first函数'); ......3
}
// 宏任务最后执行
setTimeout(() => {
console.log('settimeout 2'); .......7
}, 0);
// .then微任务
Promise.resolve().then(() => {
console.log('promise 3'); ......5
});
// 遇到new Promise直接执行,遇到.then分配到微任务队列中
new Promise((resolve, reject) => {
// new Promise里面的输出直接执行
console.log(4); ......2
// resolve暂停跳出Promise
resolve();
}).then((res) => {
console.log(5); ......6
});
// 调用first函数,输出
first();
// 同步任务直接输出
console.log('6'); ......4
MDN上给出了这样的解释:
async 函数可能包含 0 个或者多个 await 表达式。await 表达式会暂停整个 async
函数的执行进程并出让其控制权,只有当其等待的基于 promise 的异步操作被兑现或被拒绝之后才会恢复进程。
简单解释:
js会先执行 同步任务 例如题中的console.log()再执行new Promise中的console.log(),再寻找
异步任务中的微任务 promise.resolve.then(),最后寻找 异步任务中的宏任务 setTimeout(),最后执行结束。
特别注意:
await和resolve会暂停当前promise直到别的异步任务结束才继续执行。例如题中的new Promise
resolve后不继续向下执行,而是寻找其他同步任务,同步任务全部结束,寻找异步任务中的微任务,最后在执行new Promise .then的微任务,最后再寻找异步任务中的宏任务执行。
代码输出题二
console.log(1);
async function asyFunction () {
console.log(2);
await console.log(3);
await console.log(4);
console.log(5);
return 6
}
new Promise((resolve, reject) => {
console.log(10);
resolve();
}).then(res => {
console.log(11);
})
console.log(7);
setTimeout(() => {
console.log(8)
}, 0)
setTimeout(() => {
console.log(9)
}, 1000)
asyFunction().then(res => { console.log(res) });
先放出正确的答案:
此题同理,只要注意await和resolve之后会暂停,new Promise中的console.lg()会直接执行就好了。