上图中的call stack、webApi、Event loop还有Callback queue都是引擎内置的,我们是看不到的
大致分析一下代码的执行过程
我们先来分析一下下面代码的执行过程:
console.log('hello')
setTimeout(function cb1(){
console.log('heh')
},3000)
console.log('hi')
1、
2、
3、
4、
5、
6、
7、当异步函数的时间到了的时候,callback queeue会拿到这个函数。
8、
9、
其实再上面的执行过程中,还夹杂着DOM渲染,如上面,如果调用栈被清空了,异步任务还没到执行的时机,那么就会执行异步渲染。上面的web APi相当于宏任务的队列。
其实除了以上这些还有微任务的队列,
宏任务和微任务
宏任务有:setTimeout、setTimeinterval,ajax等
微任务有:Promise、async/await等
其中宏任务在DOM渲染之后执行,微任务在DOM渲染之前执行。
微任务是ES6规定的,宏任务是浏览器规定的。
总结
1、先执行同步代码,清空调用栈 2、然后从微任务队列中找微任务,放入调用栈中执行 3、DOM渲染 4、event loop一直转,直到callbackqueue中有来自webAPi的回调函数,那么就将他从callbackqueue中拿出来放到调用栈,执行回调函数
tips
async、awiat
执行async函数返回的都是Promise对象
Promise.then 成功的情况对应着await,Promise.catch 异常的情况对应着try...catch
async function test1(){
return 1;
}
async function test2(){
return Promise.resolve(2)
}
const result1 = test1();
const result2 = test2();
console.log('result1',result1);
console.log('result2',result2);
async function test3(){
const p3 = Promise.resolve(2);
// p3.then((res)=>{
// console.log(res)
// })
const data = await p3
console.log(data)
}
test3()
async function test4(){
const data = await 4//awit Promise.resolve(4)
console.log(data)
}
test4()
async function test5(){
const p4 = Promise.reject(6);
try{
await p4
}catch(e){
console.log('e',e)
}
}
test5()
```