Promise嵌套问题/async await执行顺序

/*
原则:
执行完当前promise,
会把紧挨着的then放入microtask队尾,

 

链后面的第二个then暂不处理分析,
*/

 

一、
new Promise((resolve, reject) => {
  console.log("promise1")
  resolve()
}).then( () => {
  console.log("then11")
  new Promise((resolve, reject) => {
  console.log("promise2")
  resolve()
  }).then(() => {
  console.log("then21")
  }).then(() => {
    console.log("then23")
    })
}).then(() => {
console.log("then12")
})



1.先执行同步部分代码输出 "promise1"
2.第一个then执行, 产生了promise对象, 放到microtask里(第二个then必须要等要第一个then产生的promise同步部分执行完才能放到队列里)
3.then方法构建了一个promise, 同步代码中输出 then11
4.then方法里又新建了promise 执行同步部分 输出promise2, 把第一个then放到microtask里, 把外面的then放到microtask里
5.取出microtask, 输出then21,然后里面第二个then进入microtask, 输出then12
6.输出then23




二、

 

new Promise((resolve, reject) => {
  console.log("promise1")
  resolve()
}).then(() => {
  console.log("then11")
  new Promise((resolve, reject) => {
  console.log("promise2")
  resolve()
  }).then(() => {
  console.log("then21")
  }).then(() => {
  console.log("then23")
  })
}).then(() => {
console.log("then12")
})
 
new Promise((resolve, reject) => {
console.log("promise3")
resolve()
}).then(() => {
console.log("then31")
})

 

 
1.执行外层Promise同步代码
输出promise1 第一个then进入microtask队列,第二个then不进入(因为这个要等第一个then产生的promise初始化完)

 

2.输出promise3,最下面的then进队列

 

此时队列中
----出口方向--->
[then31],[then1]

 

3.执行then1 输出了then11 构造了一个新的promise,执行同步代码promise2 then21进入队列,then12进入队列

 

---出口方向-->
[then12],[then21],[then31]

 

4.输出then31,then21,此时最后一个then,then23进入队列

 

---出口方向->
[then23],[then12],[then21]
输出 then21, then12, then23




三、
async/await

 

async function async1() {
console.log("async1 start");
await async2();
console.log("async1 end");
}

 

async function async2() {
console.log( 'async2');
}

 

console.log("script start");

 

setTimeout(function () {
console.log("settimeout");
},0);

 

async1();

 

new Promise(function (resolve) {
console.log("promise1");
resolve();
}).then(function () {
console.log("promise2");
});
console.log('script end');



//script start,async1 start,async2,promise1,script end,async1 end,promise2,settimeout
// 处理这种问题的方法:await后面跟的是一个promise对象。如果await函数,那么这个函数里的部分就应该同步执行,
// await下面的语句相当于promise.then里面的语句。

转载于:https://www.cnblogs.com/eret9616/p/10891581.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值