鐵人賽
React
javascript
nodejs
鐵人賽第23天,延續昨天的Promise
,今天我們要學習如何給出一連串的承諾,完成我們的任務!
new Promise((resolve)=>resolve("O"))
.then((result)=>result+"K")
.then((result)=>result+"L")
.then((result)=>result+"A")
.then((result)=>console.log(result+"~~!!")) // OKLA~~!!
then
,還一層一層傳遞資料下來~?這是怎麼回事??then
會使用Promise
包裝你回傳的資料,也因此,你的下一個then
,其實是上一個then
回傳的Promise
,流程就像下面這樣!酷吧!new Promise((resolve)=>resolve("O"))//Promise-0
.then((result)=>new Promise((resolve)=>resolve(result+"K"))) //接收Promise-0的訊息,回傳Promise-1
.then((result)=>new Promise((resolve)=>resolve(result+"L"))) //接收Promise-1的訊息,回傳Promise-2
.then((result)=>new Promise((resolve)=>resolve(result+"A"))) //接收Promise-2的訊息,回傳Promise-3
.then((result)=>console.log(result+"~~!!")) // 接收Promise-3的訊息,顯示OKLA~~!!
// 模擬認證Login, Check2, Check3
function Login(useInfo){
// ... do something check
let msg = "Log-in passed";
console.log(msg);
return Promise.resolve(msg);
}
function Check2(response){
// ... do something check
let msg = "Check2 passed";
console.log(msg);
return Promise.resolve(msg);
}
function Check3(response){
// ... do something check
let msg = "Check3 passed";
console.log(msg);
return Promise.resolve(msg);
}
// 開始進行一連串的認證
Login({userName:"ok168@gmail.com", password:"112233"})
.then((result)=>{
let result2 = Check2(result);
return result2;
})
.then((result)=>{
let result3 = Check3(result);
return result3;
})
.then((finalMsg)=>{
console.log("=== Finish ==="); // 所有的認證都通過,系統會在此印出 === Finish ===
})
Check3
的地方,故意讓它失敗,並在最後放一個catch
來接收失敗的訊息function Login(useInfo){
// ... do something check
let msg = "Log-in passed";
console.log(msg);
return Promise.resolve(msg);
}
function Check2(response){
// ... do something check
let msg = "Check2 passed";
console.log(msg);
return Promise.resolve(msg);
}
function Check3(response){
// ... do something check
let msg = "Check3 passed";
console.log(msg);
return Promise.resolve(msg);
}
Login({userName:"ok168@gmail.com", password:"112233"})
.then((result)=>{
let result2 = Check2(result);
return result2;
})
.then((result)=>{
let result3 = Check3(result);
// return result3;
return Promise.reject("=== Check3 is failed ===") //<-- 回傳 Promise.reject
})
.then((finalMsg)=>{
console.log("=== Finish ===");
})
.catch(fail=>console.log(fail)) //<-- 用一個catch來接收, 故會印出 === Check3 is failed ===
Promise chain
就是我們的好幫手,讓我們可以輕鬆的串接起所有的認證服務。