Promise在前端中主要用於處理異步調用,其基本使用方式通過阮一峯大佬的文檔一下就可以入手,但是最近我看了一篇文章wecTeam中,作者深山螞蟻的《高級進階:深度揭祕Promise註冊微任務和執行過程》一文,讓我對Promise的執行順序有了更深的瞭解,與此同時我也有了一個疑問,通過這篇文章與大家探討。
1. promise的異步主要發生在微任務隊列中
2. 第一個then的回調監聽最新Promise對象的resolve執行後纔會註冊進微任務隊列,之後的then回調都依賴於前一個then中的代碼執行結束。
下面的內容主要基於兩個概念討論:
(1) 當前一個then中的代碼都是同步執行的,執行結束後第二個then即可註冊進入微任務隊列。
(2) 當前一個then中有return 關鍵字,需要return的內容完全執行結束,第二個then纔會註冊進入微任務隊列。
then也分下面幾種情況:
// Case 1: 前一個then中的代碼都是同步的
new Promise( (resolve) => { resolve();})
.then(() => {console.log(1);})
.then(() => {console.log(2)});
// 輸出
// 1
// 2
// Case 2: 前一個then中的代碼 return一個Promise對象
new Promise((r,rj) => {
console.log('外p');
r();
}).then(() => {
console.log('外then1');
new Promise(((r,rj) => {
console.log('內p');
r();
})).then(() => {
console.log('內then1');
return new Promise((r, rj) => {r();});
}).then(() => {
console.log('內then2');
});
}).then(() => {
console.log('外then2');
}).then(() => {
console.log('外then3');
}).then(() => {
console.log('外then4');
});
/**
輸出結果:
"外p"
"外then1"
"內p"
"內then1"
"外then2"
"外then3"
"外then4"
"內then2"
**/
我自己疑惑的主要是Case2這種情況,爲什麼"內then2"會在"外then4"之後打印?
return new Promise((r, rj) => {r();}) 等同於
return new Promise((r, rj) => {r();}).then(()=>{console.log(1)}).then(()=>{console.log(2)}).then(()=>{console.log(3)});
這裏面究竟藏着什麼原因?