Promise是ES6出来的用来处理异步调用的方式。他是一个数据的载体 / 期约 / 承诺,一段时间后内部执行结束会返回承诺的结果。本文不讨论他的使用,只讨论promise中的同步异步。
1. Promise本身是同步的
promise是处理异步的一个方式,通常和异步操作一起出现。但是不要错误认为Promise是本身就是异步执行,其实他是同步调用。
new Promise((resolve,reject)=>{
console.log(1)
})
console.log(2)
执行结果
-----------------------------------------
1
2
2. resolve是同步的
从下面代码中可以看出resolve中的代码是立即执行的,如果resolve中是异步调用,在执行栈中就没有赋值一说,那么输出应为1,而实际是输出了100。
var num = 1
Promise.resolve(num=100)
console.log(num)
执行结果
----------------------------------------
100
上面代码也可以这么写:
var num = 1
new Promise((resolve,reject)=>{
resolve(num=100)
console.log(num)
})
console.log('同步',num)
执行结果
-----------------------------------------
100
同步 100
3.then是异步(微队列)的
js异步任务是在任务队列中排队,等主执行栈结束后才会去执行队列中满足执行条件的异步操作。
任务队列分为两种:微队列和宏队列。
微队列执行顺序优于宏队列,整体执行顺序为:执行栈-->微队列-->宏队列。
then中的任务就是排在微队列中。大部分任务执行在宏队列中如:settimeout。
new Promise((resolve, reject) => {
// 宏队列
setTimeout(() => console.log(3), 0);
resolve(2);
}).then((e) => console.log(e));// 微队列
console.log(1);
执行结果
---------------------------------------------
1
2
3
4.catch是异步(微队列)的
catch和then是相同的,都是微任务队列中的。
new Promise((resolve, reject) => {
setTimeout(()=>console.log(2),0)
throw new Error("自定义错误")
})
.then(e => console.log(e))
.catch(err=>console.log('接受到错误',err)) // 微队列
console.log(1);
执行结果
---------------------------------------------
1
接受到错误 Error: 自定义错误
...
2