JS 异步
先思考几个问题
- 描述event loop的机制,可画图
- 什么是宏任务 微任务 两者有什么区别
- promise 有多少种状态
- promise then catch 是怎样连接的
- async/await 语法糖 await 返回的是什么
- promise setTimeout async await 的顺序问题
1. event loop(事件循环/事件轮询)
- js是单线程
- 同步代码执行完再执行异步代码
- 异步代码执行,基于回调实现
这三点可以大概描述下事件循环,代码是从头到尾一行行执行的,遇到异步代码就挂起等待,继续执行下面的同步代码,同步代码执行完毕,再开始处理挂起的异步,依次循环...
- 执行栈
- web api
- callback queue
- event loop
2. promise
三个状态 pending fulfilled rejected
then catch all race
then 正常返回resolved 里面报错返回rejected catch 正常返回 resolved 里面报错返回rejected
应用案例,一个request loading ,请求失败或成功都需要关闭
let p1 = Promise.resolve(100).then((val) => {
console.log(1)
}).catch(e => {
console.log(2)
}).then(()=>{
console.log(5)
});
let p2 = Promise.reject(100).then((val) => {
console.log(1)
}).catch(e => {
console.log(2)
}).then(()=>{
console.log(5)
});
// console.log(5) 都会执行,取消loading的代码可写在一处
3. async/await
把异步当同步代码来写的语法糖 解决callback hell 问题
await 相当promise.then
如果 promise.reject 虽然try catch await xxx
for of 可以等待 await 返回
let a = function(i) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(i)
}, 1000)
})
};
(async () => {
for (let i of [1, 2, 4]) {
let bbq = await a(i);
console.log(bbq);
}
})();
generator
function sleep(duration) {
return new Promise(resovle => {
setTimeout(resovle, duration)
})
}
async function* counter() {
let i = 0;
while(true) {
await sleep(1000);
yield i++;
}
}
(async function() {
for await(let i of counter()) {
console.log(i)
}
})();
4. 微任务 宏任务
macro setTimeout setInterval dom操作 ajax micro promise async await
浏览器 宏任务 产生的微任务,会在当前宏任务结束处理,如果微任务里面还会产生微任务,会一直处理 node.js 宏任务全部执行完毕后才处理微任务
调用栈空闲的时候才会执行更新dom操作