return的类型
Promise.reslove().then(){}中的返回值的三种情况:
- 基本数据类型
- 带then方法的对象
- Promise.reslove(4)
Promise.reslove().then(){return 4;return {then: function (reslove){reslove(4)}}return Promise.reslove(4)}
首先看以下代码的输出:
Promise.resolve().then((res) => {console.log(0);return 4}).then((res)=>{console.log(res);})
Promise.resolve().then(()=>{console.log(1);}).then(()=>{console.log(2);}).then(()=>{console.log(3);}).then(()=>{console.log(5);}).then(()=>{console.log(6);})// 0142356
接下来修改return的内容:
// 修改为return {then: function (resolve) {resolve(4)}
// 0124356
接下来再修改return的内容:
// 修改为return Promise.reslove(4)
// 0123456
为什么不同的return 值会产生不同的执行顺序?
首先,我们要明确一点:微任务的执行顺序是根据它们的注册顺序执行的
其次:.then(){}中的 return 其实是一个Promise.reslove()包装后的值
为了方便描述,我们将第一个Promise.reslove()称为P1,第二个Promise.reslove()称为P2。
在第一种情况:return 4
执行顺序为:
- 执行 P1.then(0)完毕,返回一个Promise.reslove(4),注册 P1.then(0){}.then(4)
- 执行 P2.then(1),注册 P2.then(1){}.then(2)
- 执行 P1.then(0){}.then(4),不再有新的then注册
- 执行 P2.then(1){}.then(2),注册 P2.then(1){}.then(2){}.then(3)
- P2继续执行
- 输出为:0、1、4、2、3、5、6
第二种情况
执行顺序为:
- 执行 P1.then(0),返回一个Promise.reslove({then: function(reslove){reslove(4)}})
- 执行 P2.then(1),注册 P2.then(1){}.then(2)
- 执行 Promise.reslove.then(reslove),注册 P1.then(0){}.then(4)
- 执行 P2.then(1){}.then(2),注册 P2.then(1){}.then(2){}.then(3)
- 执行 P1.then(0){}.then(4),不再有新的then注册
- 执行 P2.then(1){}.then(2){}.then(3),注册 P2.then(1){}.then(2){}.then(3){}.then(4)
- P2继续执行
- 输出为:0、1、2、4、3、5、6
第三种情况
执行顺序为:
- 执行 P1.then(0),返回一个 Promise.reslove(Promise.reslove(4))- 执行 P2.then(1),注册 P2.then(1){}.then(2)- 执行 Promise.reslove(Promise.reslove(4)),返回一个Promise.reslove(4)。内层的 Promise.reslove(4)没有.then注册- 执行 P2.then(1){}.then(2),注册 P2.then(1){}.then(2){}.then(3)- 执行 Promise.reslove(4),注册外层的 P1.then(0){}.then(4)- 执行 P2.then(1){}.then(2){}.then(3),注册 P2.then(1){}.then(2){}.then(3){}.then(4)- 执行 P1.then(0){}.then(4),不再有新的then注册- 执行 P2.then(1){}.then(2){}.then(3){}.then(4),注册 P2.then(1){}.then(2){}.then(3){}.then(4){}.then(5)- 执行 P2.then(1){}.then(2){}.then(3){}.then(4){}.then(5),注册 P2.then(1){}.then(2){}.then(3){}.then(4){}.then(5){}.then(6)- 执行 P2.then(1){}.then(2){}.then(3){}.then(4){}.then(5){}.then(6),没有新的.then 注册- 输出为:0、1、2、3、4、5、6
所以让咱们来一次套娃:
Promise.resolve().then((res) => {console.log(0);return Promise.resolve().then(() => {return {then: function (resolve) {resolve(Promise.resolve(4))}}})}).then((res) => {console.log(res);})
Promise.resolve().then((res) => {console.log(1);}).then((res) => {console.log(2);}).then((res) => {console.log(3);}).then(() => {console.log(5);}).then(() => {console.log(6);}).then(() => {console.log(7);}).then(() => {console.log(8);})
输出是 0、1、2、3、5、6、7、4、8