promise
作用,在宏任务假死情况下的异步操作
promise(resolve,reject)
参数一是返回成功,参数二是返回失败
promise().then().then()
.then()链式操作解决了地狱回调(操作复杂,且不容易改变逻辑代码)
getpromise(num) {
return new Promise((resolve, reject) => {
if (num > 1) {
return resolve;
} else {
return reject;
}
});
},
computes() {
this.getpromise(3).then((resolve, reject) => {
console.log(resolve);
console.log(reject);
});
},
async与await
直译 await是等待
async与await 的出现优化了.then()的操作,当方法内含有await时,async必须定义
console.log("0") //同步
async asyncFN() { // 在promise内 async会是同步状态
console.log("A"); //当前作用域下的同步
const a1 = await this.getpromise(1);
const a2 = await this.getpromise(2);
const a3 = await this.getpromise(3);
console.log(a1,a2,a3);
console.log("D")
},
console.log("F") // 同步
这是一个经典面试题
//执行顺序答案: 0 A F a1 a2 a3 D
前提在同等级的作用域下
同步 》 微任务(nextick >function | promise内的then) 》宏任务
解释:
promise的then前的位置属于同步.
promise的then后的位置与其他函数的微任务比较,其他微任务的级别要高
知识点 :
- 在async方法中,第一个await之前的代码会同步执行,await之后的代码会异步执行
- 先执行宏任务在执行所有的微任务
宏任务与微任务
异步发划分
宏任务:
1.异步Ajax请求
2.setTimeout , setInterval
3.文件操作
4.其它宏任务
微任务:
1.promise.then catch 和 finally
2.process.nextTick
3.其它微任务
题目二:
//宏任务
setTimeout(() => {
console.log(2)
},0)
//微任务 级别略高
fun(()=>{
console.log(3)
})
// 微任务
process.nextTick(()=>{
console.log(4)
})
//
new Promise ((resolve,reject) =>{
console.log(5) //同步
if(reject){
reject()
}else{
resolve() //有这个返回结果才会执行then
}
}).then(()=>{
console.log(6) //微任务
})
console.log(1) // 同步
// 5 1 4 3 6 2