ရိုးရိုးလေး ရှင်းပြမယ်
Promise ကို ရိုးရိုးလေး ပြောရရင်
Promise ဆိုတာ 'အခု မရသေးတဲ့ ရလဒ်' ကို ကိုယ်စားပြုတဲ့ object တစ်ခုပါ။ File ဖတ်တာ၊ server ဆီ request ပို့တာ၊ timer စောင့်တာလို အချိန်ယူရတဲ့ အလုပ်တွေက ရလဒ်ကို ချက်ချင်း မပေးနိုင်ပါဘူး။ အဲဒီအစား Promise တစ်ခုကို ချက်ချင်း ပြန်ပေးပြီး 'ပြီးတာနဲ့ အောင်မြင်တဲ့ value ဒါမှမဟုတ် error တစ်ခုခုကို ပေးမယ်' လို့ ကတိပေးထားပါတယ်။
စားသောက်ဆိုင်က ပေးတဲ့ မှာယူမှု နံပါတ်ပြားလေးကို စဉ်းစားကြည့်ရအောင်။ ပြားလေးက အစားအစာ မဟုတ်ပါဘူး၊ ဒါပေမဲ့ နောက်မှ အစားအစာ ရမယ်၊ ဒါမှမဟုတ် 'ကုန်သွားပြီ' လို့ အကြောင်းကြားမယ်ဆိုတဲ့ အာမခံချက်ပါ။ စောင့်နေရင်း တခြားအလုပ် လုပ်လို့ရပြီး ရလဒ်ရောက်တဲ့အခါ .then() က အောင်မြင်တဲ့ value ကို၊ .catch() က error ကို ကိုင်တွယ်ပေးပါတယ်။
Problem → Why → Solution
ပြဿနာ: chain က စောပြီး ပြီးသွားတယ်
User ကို load လုပ်ပြီးမှ သူ့ order တွေကို load လုပ်ပြီး နောက်ဆုံးမှာ 'done' လို့ log ထုတ်ချင်တယ် ဆိုပါစို့။ အောက်က code က ကြည့်ရတာ မှန်နေပေမဲ့ 'done' က order တွေ မရောက်ခင် အရင် print ထွက်လာပြီး ဒုတိယ then က undefined ကိုပဲ ရပါတယ်။ Order load ရင်း error တက်ရင်လည်း catch က မမိဘဲ unhandled rejection ဖြစ်သွားပါတယ်။
loadUser(7)
.then((user) => {
loadOrders(user.id); // starts the work but does not return it
})
.then((orders) => {
console.log(orders); // undefined
console.log("done"); // runs before the orders have loaded
})
.catch((error) => console.error(error)); // never sees a loadOrders failureဘာကြောင့် ဒီလို ဖြစ်တာလဲ
then တိုင်းက Promise အသစ်တစ်ခု ပြန်ပေးပြီး အဲဒီ Promise ကို callback ရဲ့ return value နဲ့ settle လုပ်ပါတယ်။ Callback က ဘာမှ return မလုပ်ရင် undefined နဲ့ ချက်ချင်း fulfilled ဖြစ်သွားလို့ chain က နောက်တစ်ဆင့်ကို ဆက်သွားပါတယ်။ loadOrders ရဲ့ Promise ကို return လုပ်လိုက်မှသာ chain က အဲဒါကို စောင့်ပြီး သူ့ error ကိုလည်း catch ဆီ ပို့ပေးပါတယ်။
Core concept: တစ်ကြိမ်တည်း settle ဖြစ်ပြီး chain လုပ်လို့ရတဲ့ object
Promise တစ်ခုမှာ state သုံးမျိုး ရှိပါတယ်: pending (စောင့်နေဆဲ)၊ fulfilled (value နဲ့ အောင်မြင်ပြီ)၊ rejected (reason နဲ့ ကျရှုံးပြီ)။ Pending ကနေ ကျန်နှစ်ခုထဲက တစ်ခုကို တစ်ကြိမ်ပဲ ပြောင်းနိုင်ပြီး settle ဖြစ်ပြီးရင် ပြန်မပြောင်းတော့ပါဘူး။ resolve ကို နှစ်ခါ ခေါ်တာ၊ resolve ပြီးမှ reject ခေါ်တာတွေကို လျစ်လျူရှုပါတယ်။
new Promise ကို ပေးတဲ့ executor function က ချက်ချင်း synchronous အနေနဲ့ run ပါတယ်။ အဲဒီထဲမှာ အလုပ်ကို စတင်ပြီး ပြီးတဲ့အခါ resolve(value) ဒါမှမဟုတ် reject(error) ကို ခေါ်ပါတယ်။ Reject လုပ်တဲ့အခါ string အစား Error object ကို သုံးတာ ကောင်းပါတယ်၊ stack trace ပါလာပြီး error.message ကိုလည်း နေရာတိုင်းမှာ တူတူ ဖတ်လို့ရလို့ပါ။
then, catch, finally တို့က Promise အသစ်ကို ပြန်ပေးတဲ့အတွက် chain ချိတ်လို့ ရပါတယ်။ Callback က ရိုးရိုး value ကို return ရင် နောက်တစ်ဆင့်က အဲဒီ value ကို ရပါတယ်။ Promise ကို return ရင် chain က အဲဒါ settle ဖြစ်တဲ့အထိ စောင့်ပါတယ်။ throw လုပ်ရင် ဒါမှမဟုတ် rejected Promise ကို return ရင် ကြားက then တွေကို ကျော်ပြီး အနီးဆုံး catch ဆီ တန်းရောက်ပါတယ်။ catch ကလည်း value တစ်ခု return လုပ်ရင် chain က ပုံမှန်အတိုင်း ပြန်ဆက်သွားပါတယ်။
Promise ချက်ချင်း settle ဖြစ်ပြီးသားဆိုရင်တောင် then callback တွေက လက်ရှိ synchronous code အားလုံး ပြီးမှ microtask queue ကနေ run ပါတယ်။ ဒါကြောင့် Promise.resolve(1).then(log) ရဲ့ နောက်က console.log က အရင် print ထွက်ပါတယ်။ Promise တွေမှာ built-in cancellation မပါပါဘူး၊ ဒါကြောင့် fetch လို API တွေက AbortController ကို သီးခြား သုံးပါတယ်။
| Combinator | ဘယ်အခါ settle ဖြစ်လဲ |
|---|---|
| Promise.all | အားလုံး fulfilled ရင် value array နဲ့၊ တစ်ခု reject ရင် ချက်ချင်း reject |
| Promise.allSettled | အားလုံး ပြီးမှ { status, value | reason } array နဲ့ အမြဲ fulfilled |
| Promise.race | ပထမဆုံး settle ဖြစ်တဲ့ Promise အတိုင်း |
| Promise.any | ပထမဆုံး fulfilled ဖြစ်တဲ့ value နဲ့၊ အားလုံး reject ရင် AggregateError |
- အလုပ်စပြီး pending slip ချက်ချင်းရ
- resolve ဒါမှမဟုတ် reject တစ်ကြိမ်ပဲ
- Sync code ပြီးမှ then/catch run
- Return value က နောက် then ဆီ
- Throw က အနီးဆုံး catch ဆီ ခုန်
then callback ထဲမှာ async အလုပ်တစ်ခု စလိုက်ရင် အဲဒီ Promise ကို အမြဲ return ပါ၊ မဟုတ်ရင် chain က မစောင့်ပါဘူး။
အထွေထွေ ပုံစံ
const promise = new Promise((resolve, reject) => {
// start the work; later call resolve(value) or reject(new Error(msg))
});
promise
.then((value) => nextValueOrPromise)
.catch((error) => fallbackValue)
.finally(() => cleanup());
Promise.all([taskA(), taskB()]).then(([a, b]) => use(a, b));Executor ထဲမှာ အလုပ်ကို စပြီး တစ်ကြိမ်တည်း settle လုပ်ပါ။ then ထဲက return value က နောက်တစ်ဆင့်ရဲ့ input ဖြစ်ပြီး catch က အပေါ်က ဘယ်အဆင့်ကလာတဲ့ error ကိုမဆို ဖမ်းပါတယ်။ finally က cleanup အတွက်ပါ၊ value ကို မပြောင်းပါဘူး။
Worked example: Promise တစ်ခု ဖန်တီးပြီး ကိုင်တွယ်ခြင်း
ဒီ example က Promise တစ်ခုကို ကိုယ်တိုင် ဖန်တီးပြီး ချက်ချင်း resolve လုပ်ပါတယ်။ success ကို false လို့ ပြောင်းကြည့်ပါ၊ အဲဒီအခါ then ကို ကျော်ပြီး catch က run ပါလိမ့်မယ်။ Promise တစ်ခုမှာ success လမ်းကြောင်းနဲ့ failure လမ်းကြောင်း နှစ်ခု ရှိပြီး settle ဖြစ်တဲ့အချိန်မှာ တစ်ခုတည်းကိုပဲ ရွေးတယ်ဆိုတာကို ဒီလိုနည်းနဲ့ မြင်ရပါတယ်။
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("The operation was successful!");
} else {
reject("The operation failed.");
}
});
myPromise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
});Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Create the Promise
const myPromise = new Promise((resolve, reject) => {Executor function က ချက်ချင်း run ပြီး resolve နဲ့ reject ဆိုတဲ့ function နှစ်ခုကို လက်ခံပါတယ်။ ဒီအချိန်မှာ myPromise က pending ဖြစ်နေပါသေးတယ်။
- Fulfil it
resolve("The operation was successful!");resolve ကို ခေါ်လိုက်တာနဲ့ Promise က ဒီ string value နဲ့ fulfilled ဖြစ်သွားပြီး နောက်ထပ် resolve/reject ခေါ်တာတွေကို လျစ်လျူရှုပါတယ်။
- The failure path
reject("The operation failed.");success က false ဖြစ်မှသာ ဒီ line က run ပါတယ်။ လက်တွေ့ code မှာ reject(new Error("The operation failed.")) လို့ Error object နဲ့ ရေးတာ ပိုကောင်းပါတယ်။
- Handle success
.then((message) => {Fulfilled value က message ထဲ ရောက်လာပါတယ်။ ဒီ callback က script ရဲ့ synchronous အပိုင်း ပြီးမှ run ပါတယ်။
- Handle failure
.catch((error) => {Promise reject ဖြစ်ရင်၊ ဒါမှမဟုတ် then callback ထဲမှာ throw ဖြစ်ရင် ဒီ catch က ဖမ်းပါတယ်။ ဒီ run မှာတော့ မခေါ်ခံရပါဘူး။
The operation was successful!Chain တစ်ခုထဲမှာ value နဲ့ error ဘယ်လို စီးဆင်းလဲ
အောက်က code ကို run မလုပ်ခင် print ထွက်မယ့် အစီအစဉ်ကို ခန့်မှန်းကြည့်ပါ။ Number တွေက တကယ် run တဲ့ အစီအစဉ်ပါ။ Synchronous log နှစ်ခုက အရင်ထွက်ပြီး ပထမ then က return လုပ်တဲ့ length က ဒုတိယ then ဆီ ရောက်ပါတယ်။ throw ပြီးနောက် တတိယ then ကို ကျော်ပြီး catch ဆီ တန်းရောက်ကာ finally က နောက်ဆုံးမှာ အမြဲ run ပါတယ်။
console.log("1: synchronous code runs first");
Promise.resolve("ready")
.then((value) => {
console.log("3: then received", value);
return value.length; // a plain value becomes the next step's input
})
.then((length) => {
console.log("4: next then received", length);
throw new Error("disk full");
})
.then(() => console.log("skipped: a rejection jumps over this"))
.catch((error) => console.log("5: catch received", error.message))
.finally(() => console.log("6: finally runs either way"));
console.log("2: still synchronous");Output ကို ကိုယ်တိုင် စစ်ပါ
Print ထွက်တာက 1, 2, 3 (ready), 4 (5), 5 (disk full), 6 ပါ။ "skipped" line က ဘယ်တော့မှ မပေါ်ပါဘူး။
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ Promise
ယနေ့ JavaScript ရဲ့ async API အများစုက Promise ကို ပြန်ပေးပါတယ်: browser နဲ့ Node ရဲ့ fetch၊ Node ရဲ့ fs/promises၊ database driver အများစုနဲ့ async function တိုင်းပါ။ ဒါကြောင့် Promise ကို နားလည်တာက ဒီ API တွေ အားလုံးကို နားလည်ဖို့ အခြေခံပါ။ Async/await (နောက် lesson) ကလည်း Promise အပေါ်မှာ တည်ဆောက်ထားတာပါ။
- Dashboard page: profile နဲ့ settings ကို တစ်ခုနဲ့တစ်ခု မမှီခိုတဲ့အတွက် Promise.all နဲ့ တစ်ပြိုင်နက် load လုပ်ပြီး နှစ်ခုလုံး လိုအပ်တဲ့အတွက် တစ်ခု fail ရင် error page ပြပါတယ်။
- Optional widget တွေ (ကြော်ငြာ၊ အကြံပြုချက်) အတွက် Promise.allSettled ကို သုံးပါတယ်၊ widget တစ်ခု fail ရင် အဲဒါကိုပဲ ဖျောက်ပြီး ကျန်တာတွေကို ပြနေနိုင်ပါတယ်။
- Loading spinner ကို finally ထဲမှာ ပိတ်တဲ့အတွက် success ဖြစ်ဖြစ် error ဖြစ်ဖြစ် spinner က လည်နေဆဲ မကျန်ခဲ့ပါဘူး။
- Callback ပုံစံ API အဟောင်းတွေကို new Promise နဲ့ (ဒါမှမဟုတ် Node မှာ util.promisify နဲ့) wrap လုပ်ပြီး codebase တစ်ခုလုံးကို Promise ပုံစံတစ်မျိုးတည်း ဖြစ်အောင် လုပ်လေ့ရှိပါတယ်။ Error-first callback ရဲ့ err ကို reject ဆီ၊ result ကို resolve ဆီ ပို့ပေးရုံပါပဲ။
အမှားများ
Promise နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ
then ထဲက Promise ကို return မလုပ်ခြင်း
then((user) => { loadOrders(user.id); }) က အလုပ်ကို စပေမဲ့ chain က မစောင့်ပါဘူး၊ နောက်တစ်ဆင့်က undefined ရပြီး loadOrders ရဲ့ error က catch ဆီ မရောက်ပါဘူး။ return loadOrders(user.id) လို့ ရေးပါ၊ ဒါမှမဟုတ် curly brace မပါတဲ့ arrow function သုံးပါ။
catch မထည့်ခြင်း
Rejection ကို ဘယ်သူမှ မကိုင်တွယ်ရင် browser က console မှာ Uncaught (in promise) error ပြပြီး ခေတ်မီ Node.js version တွေကတော့ default အနေနဲ့ process ကို ရပ်ပစ်ပါတယ်။ Chain တိုင်းကို catch နဲ့ အဆုံးသတ်ပါ၊ ဒါမှမဟုတ် ကိုင်တွယ်မယ့်သူဆီ return ပြန်ပေးပါ။
Promise.all ကို 'တချို့ fail ရလည်း ရတယ်' ဆိုတဲ့နေရာမှာ သုံးခြင်း
Promise.all က ပထမဆုံး rejection နဲ့ ချက်ချင်း reject ဖြစ်ပြီး အောင်မြင်ပြီးသား value တွေကိုပါ ဆုံးရှုံးစေပါတယ်။ ရလဒ်တစ်ခုချင်းစီကို သီးခြား လိုချင်ရင် Promise.allSettled ကို သုံးပါ။ Promise.all က ကျန်တဲ့ အလုပ်တွေကို ရပ်ပေးတာလည်း မဟုတ်ပါဘူး၊ နောက်ကွယ်မှာ ဆက် run နေပါတယ်။
Best Practices
Best practices
- reject လုပ်တဲ့အခါ string မဟုတ်ဘဲ new Error(...) ကို သုံးပါ။
- Chain ကို ပြားပြားလေး ထားပါ: then ထဲမှာ then ထပ်မအောင်းဘဲ Promise ကို return ပါ။
- တစ်ခုနဲ့တစ်ခု မမှီခိုတဲ့ အလုပ်တွေကို အရင်စပြီး Promise.all နဲ့ စုစောင့်ပါ။
- Cleanup (spinner ပိတ်တာ၊ connection ပိတ်တာ) ကို finally ထဲမှာ ထားပါ။
Mini challenge
Mini challenge: dashboard loader
Timer နဲ့ အတုလုပ်ထားတဲ့ service သုံးခု (profile, settings, ads) ကို Promise နဲ့ ညှိပါ။ Profile နဲ့ settings ကို တစ်ပြိုင်နက် load လုပ်ပြီး summary တစ်ကြောင်း ထုတ်ပါ။ နောက် settings နဲ့ ads ကို Promise.all နဲ့ စမ်းကြည့်ပြီး fail ဖြစ်တာကို catch မှာ ဖမ်းကာ allSettled report တစ်ခုနဲ့ ဆက်သွားပါ။
- delay(ms, value) က ms ကြာပြီးမှ value နဲ့ resolve ဖြစ်ရမယ်
- failAfter(ms, message) က ms ကြာပြီးမှ Error နဲ့ reject ဖြစ်ရမယ်
- loadDashboard က Promise.all ကို သုံးပြီး string တစ်ခု ပြန်ပေးရမယ်
- loadEverything က allSettled ရလဒ်ကို "ok" ဒါမှမဟုတ် "failed: ..." array အဖြစ် ပြောင်းရမယ်
- Chain တစ်ခုတည်းမှာ return အမှန်တွေနဲ့ ချိတ်ပါ၊ nested then မသုံးပါနဲ့
function delay(ms, value) {
// TODO: return a Promise that resolves with value after ms (use setTimeout)
}
function failAfter(ms, message) {
// TODO: return a Promise that rejects with new Error(message) after ms
}
const loadProfile = () => delay(30, { name: "Aung Kyaw" });
const loadSettings = () => delay(10, { theme: "dark" });
const loadAds = () => failAfter(20, "ads service down");
function loadDashboard() {
// TODO: run loadProfile and loadSettings together,
// resolve with "<name> uses the <theme> theme"
}
function loadEverything() {
// TODO: Promise.allSettled for profile + ads, map each result to
// "ok" or "failed: <message>"
}
// TODO: one flat chain:
// 1. print "all:" + loadDashboard() result
// 2. return Promise.all([loadSettings(), loadAds()])
// 3. catch: print "all rejected:" + message, return loadEverything()
// 4. print "allSettled:" + the reportရလဒ်: all: Aung Kyaw uses the dark theme၊ all rejected: ads service down၊ allSettled: [ 'ok', 'failed: ads service down' ] ဆိုတဲ့ line သုံးကြောင်းကို ဒီအစီအစဉ်အတိုင်း print ထုတ်ရပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
Promise.all ရဲ့ ရလဒ်ကို ([profile, settings]) => ... လို destructure လုပ်လို့ရပါတယ်။ allSettled ရလဒ်တစ်ခုချင်းစီမှာ status က "fulfilled" ဒါမှမဟုတ် "rejected" ဖြစ်ပြီး rejected ရင် reason.message ကို ဖတ်ပါ။
အဖြေ ကြည့်ရန်
function delay(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
function failAfter(ms, message) {
return new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
}
const loadProfile = () => delay(30, { name: "Aung Kyaw" });
const loadSettings = () => delay(10, { theme: "dark" });
const loadAds = () => failAfter(20, "ads service down");
function loadDashboard() {
return Promise.all([loadProfile(), loadSettings()]).then(([profile, settings]) => {
return `${profile.name} uses the ${settings.theme} theme`;
});
}
function loadEverything() {
return Promise.allSettled([loadProfile(), loadAds()]).then((results) =>
results.map((r) => (r.status === "fulfilled" ? "ok" : `failed: ${r.reason.message}`)),
);
}
loadDashboard()
.then((summary) => {
console.log("all:", summary);
return Promise.all([loadSettings(), loadAds()]);
})
.catch((error) => {
console.log("all rejected:", error.message);
return loadEverything();
})
.then((report) => console.log("allSettled:", report));Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Promise က pending ကနေ fulfilled ဒါမှမဟုတ် rejected ကို တစ်ကြိမ်တည်း settle ဖြစ်ပြီး ပြန်မပြောင်းပါဘူး။
- then/catch/finally တိုင်းက Promise အသစ်ပြန်ပေးပါတယ်: return value က ရှေ့ဆက်သွားပြီး throw က အနီးဆုံး catch ဆီ ခုန်ပါတယ်။
- then callback တွေက လက်ရှိ synchronous code ပြီးမှ run ပါတယ်။
- Promise.all က အားလုံး လိုအပ်တဲ့အခါ၊ Promise.allSettled က ရလဒ်တစ်ခုချင်း လိုတဲ့အခါ သုံးပါ။
MDN — Asynchronous JavaScript — MDN Web Docs