then
then
函式的會接收兩個回撥函式,一個是 onFulfilled
函式,一個是 onRejected
函式
如果這兩個回撥函式沒有寫返回值,預設會 return undefined;
進入下一個函式的 onFulfilled
函式中
const p = new Promise((resolve, reject) => {
resolve(22);
});
p.then(
(success1) => {
console.log("success1", success1); // "success2" 22
// 沒寫 return 預設返回 return undefined
},
(err1) => {
console.log("err1", err1);
}
).then(
(success2) => {
console.log("success2", success2); // "success2" undefined
},
(err2) => {
console.log("err2", err2);
}
);
在這兩個回撥中 return xxx
,相當於呼叫 return new Promise((resolve) => resolve(xxx));
const p = new Promise((resolve, reject) => {
resolve(22);
});
p.then(
(success1) => {
return new Promise((resolve, reject) => resolve("success"));
// 等價於
return "success";
},
(err1) => {
console.log("err1", err1);
}
).then(
(success2) => {
console.log("success2", success2); // "success2" "success"
},
(err2) => {
console.log("err2", err2);
}
);
在 onFulfilled
函式和 onRejected
函式中預設返回的都是成功,如果需要返回失敗需要顯示呼叫 reject
或者用 throw
丟擲錯誤可以
const p = new Promise((resolve, reject) => {
resolve(22);
});
p.then(
(success1) => {
return new Promise((resolve, reject) => reject("error"));
// 等價於
// throw "error";
},
(err1) => {
console.log("err1", err1);
}
).then(
(success2) => {
console.log("success2", success2);
},
(err2) => {
console.log("err2", err2); // "err2" error
}
);
總結:在 then
回撥中 return xxx
會被自動包裝成 return new Promise((resolve) => resolve(xxx));
,
catch
catch
是用來處理 rejected
狀態,是 then
函式的一種特例,相當於 then(null, (err) => {});
catch
為什麼能捕獲前面的錯誤?
在 onRejected
函式中,如果沒有顯示丟擲錯誤,預設會 return undefined;
進入一下個 onFulfilled
函式
finally
finally
不管當前 promise
是什麼狀態都會執行,也是 then
函式的一種特例,相當於 `then(result => result, err => new Promsie((\_, reject) => reject(err)));
Promise.resolve
Promise.resolve
是 Promise
在 fulfilled
狀態時的簡寫,相當於 new Promise(resolve => resolve(xxx))
onFulfilled
函式接收引數
當引數是普通引數時,會直接傳遞給後面
then
函式new Promise((resolve) => resolve({ name: "uccs" })).then((data) => { console.log(data); });
當引數是
Promise
物件時,後面的then
會根據傳遞的Promise
物件的狀態變化執行哪一個回撥const p = new Promise((resolve, reject) => { setTimeout(resolve, 1000, "我執行了"); }); new Promise((resolve) => resolve(p)).then((data) => { console.log(data); });
具有
then
方法的物件用這種這種方式,如果需要改變
Promise
狀態是,不能使用return
形式,這個then
方法也是有兩個回撥函式的:onFulfilled
和onRejected
const thenable = { then(resolve, reject) { console.log("thenable"); }, }; new Promise((resolve) => resolve(thenable)).then((data) => { console.log(data); });
Promise.reject
Promise.reject
是 Promise
在 rejected
狀態是的簡寫,相當於 new Promise((_, reject) => reject(xxx))
onRejected
函式不管接收什麼引數,都會原封不動的向後傳遞,作為後續方法的引數