前言
之前一直搞不太明白then的执行机制,对最近这几天的研究做个总结笔记
then()方法的概念不用多说了,大概屡屡
是promise实例状态发生变化会回调then方法里的回调函数,fulfilled状态会执行第一个参数的回调,rejected状态会执行第二个参数的回调。
then方法调用后自己也会返回一个为fulfilled状态的promise实例
catch方法也是会返回fulfilled状态的promise实例
所以then()后面可以继续链式调用then()。
基于then的嵌套整理出以下有几种常见的方式:
then()里有无return值
无return
new Promise((resolve, reject)=>{
resolve()
}).then(()=>{
console.log(1)
}).then(()=>{
console.log(2)
})
//输出 :
//1
//2
第一个then执行完后自身返回了一个fulfilled状态的promise实例,所以第二个then属于他的下一轮微任务,也跟着执行了回调。
无return 但里面有宏任务
new Promise((resolve, reject)=>{
resolve()
}).then(()=>{
setTimeout(()=>{
console.log(1)
},1000)
}).then(()=>{
console.log(2)
})
//输出:
//2
//1s后 1
第一个then调用后里面是一个延迟函数宏任务,挂起来,这时候第一then的返回已经是fulfilled状态的promise实例,所以会继续调用后面的第二个then,打印出2,然后轮训发现后面没有别的同步任务了,开始执行延迟宏任务 打印出1.
无return 里面再次执行promise
new Promise((resolve, reject)=>{
resolve()
}).then(()=>{
new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log(1)
},1000)
})
}).then(()=>{
console.log(2)
})
//2
//1s后 1
第一个then执行里面是promise,promise体内也算是同步任务执行,然后里面是延迟宏任务挂载到队列上,
这时候第一个then的返回
有return 值
new Promise((resolve, reject)=>{
resolve()
}).then(()=>{
return 123
}).then((res)=>{
console.log(res,'------')
})
//123
new Promise((resolve, reject)=>{
resolve()
}).then(()=>{
setTimeout(()=>{
return 123
})
}).then((res)=>{
console.log(res,'------')
})
// undefined '------'
虽然第一个then有return值,但是包在了延迟任务里,就挂载起来了,这时候还是会继续执行第二个then返回的undefined
有return 值 但是return的是promise实例
new Promise((resolve, reject)=>{
resolve()
}).then(()=>{
return new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log(1)
resolve()
},2000)
})
}).then(()=>{
console.log(2)
})
如果then回调函数里 return的是 另一个promise 实例 该then后面的回调函数 会等待这个promise实例执行状态改变后才会执行
tcatch返回的也是fulfilled 状态的promise实例
const p = new Promise((resolve, reject)=>{
reject()
}).catch(()=>{
return 123
}).then((res)=>{
console.log(res)
})
//123
这道题也很有意思
拿来分析下
new Promise((resolve, reject) => {
console.log(1);
resolve();
})
.then((a) => {
console.log(2);
new Promise((resolve,reject) => {
console.log(3);
resolve();
})
.then((c) => {
console.log(4);
})
.then((d) => {
console.log(6);
})
})
.then((b) => {
console.log(5);
});
执行promise 先打印出1,然后resolve函数promise状态变为了fulfilled,可以执行第一个then也就是a回调,a回调后面还有一个then是b回调,但是b是必须要等待a返回的的实例状态变为fulfilled才会执行,所以继续走a内部的任务打印出2,然后执行一个新的promise打印出3,该promise执行resolve状态变为fulfilled执行c回调打印出4,后面的then方法d属于c状态变化后执行的异步会挂载到下一轮微任务中,这时候a内部的任务走完,没有返回值默任返回是undefined,a状态变为fulfilled,开始轮训新的任务队列,执行了第一轮微任务b打印出5,接着执行后面一轮的微任务c的状态变化,执行d回调打印出6;
输出
1
2
3
4
5
6