Promise嵌套問題/async await執行順序

/*
原則:
執行完當前promise,
會把緊挨着的then放入microtask隊尾,

 

鏈後面的第二個then暫不處理分析,
*/

 

1、
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




2、

 

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




3、
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裏面的語句。
相關文章
相關標籤/搜索