前言
本文已代碼解讀的方式來學(xué)習(xí)整個過程。這里提供了五段代碼,如果你都能理解清楚,完全正確的說出 output 過程,那么厲害大牛如你,我在這里給你豎個大拇指,祝賀你對 Promise 的執(zhí)行過程已經(jīng)了如指掌。
當然可能你也未必真正了解核心,能正確的理解和解釋這個過程,不妨看看題目的解釋。
當然如果是和我一樣的菜鳥,那么我們就一起來看看吧~
看答案前,先自己默默算下輸出結(jié)果吧。
第一段代碼
new Promise((resolve, reject) => {
console.log("外部promise");
resolve();
})
.then(() => {
console.log("外部第一個then");
return new Promise((resolve, reject) => {
console.log("內(nèi)部promise");
resolve();
})
.then(() => {
console.log("內(nèi)部第一個then");
})
.then(() => {
console.log("內(nèi)部第二個then");
});
})
.then(() => {
console.log("外部第二個then");
});
這個輸出還是比較簡單的,外部第一個 new Promise 執(zhí)行,執(zhí)行完 resolve ,然后執(zhí)行外部第一個 then 。外部第一個 then 方法里面 return 一個 Promise,這個 return ,代表 外部的第二個 then 的執(zhí)行需要等待 return 之后的結(jié)果。當然會先執(zhí)行完內(nèi)部兩個 then 之后,再執(zhí)行 外部的第二個 then ,機智如你,完全正確。
output:
外部promise
外部第一個then
內(nèi)部promise
內(nèi)部第一個then
內(nèi)部第二個then
外部第二個then