ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
စားသောက်ဆိုင်က စားပွဲထိုး တစ်ယောက်ကို စဉ်းစားကြည့်ပါ။ Order ကို မီးဖိုချောင်ကို ပို့ပြီးရင် ဟင်းကျက်သည်အထိ မီးဖိုချောင်ရှေ့မှာ ရပ်မစောင့်ပါဘူး၊ တခြား စားပွဲတွေမှာ order ဆက်ယူပါတယ်။ ဟင်းကျက်တာနဲ့ မီးဖိုချောင်က ခေါ်လိုက်ရင် ပြန်လာယူပါတယ်။ Node.js ရဲ့ thread တစ်ခုတည်းက ဒီ စားပွဲထိုးလို အလုပ်လုပ်ပါတယ် — file ဖတ်တာ၊ database မေးတာကို operating system ဆီ လွှဲပြီး ကြားထဲမှာ request တခြားတွေကို ဆက်ကိုင်ပါတယ်။
Promise က မီးဖိုချောင်က ပေးလိုက်တဲ့ order လက်မှတ်လိုပါ။ အခု ဟင်းမရသေးပေမယ့် နောက်မှ ဟင်း (value) ရမယ်၊ ဒါမှမဟုတ် "ကုန်သွားပြီ" (error) ဆိုတဲ့ အဖြေ တစ်ခုခု ရမယ်လို့ ကတိပေးထားပါတယ်။ await ဆိုတာ "ဒီ function ထဲမှာတော့ ဒီလက်မှတ်ရဲ့ အဖြေ ရမှ ဆက်လုပ်မယ်" လို့ ပြောတာပါ၊ စားပွဲထိုးကတော့ တခြား အလုပ်တွေ ဆက်လုပ်နေပါတယ်။
Problem → Why → Solution
ပြဿနာ: await မေ့တာနဲ့ မလိုဘဲ တန်းစီစောင့်တာ
Async code မှာ အဖြစ်အများဆုံး bug နှစ်ခု ရှိပါတယ်။ ပထမတစ်ခုက await မေ့တာပါ — readFile() က data ကို မပြန်ဘဲ Promise ကို ချက်ချင်း ပြန်ပေးလို့ JSON.parse() က "[object Promise]" ဆိုတဲ့ string ကို parse လုပ်ဖို့ ကြိုးစားပြီး SyntaxError ပေးပါတယ်။ ဒုတိယတစ်ခုက တစ်ခုနဲ့တစ်ခု မမှီခိုတဲ့ အလုပ်တွေကို await နဲ့ တစ်ခုပြီးမှ တစ်ခု run တာပါ — 300ms စီကြာတဲ့ request နှစ်ခုက 300ms နဲ့ ပြီးနိုင်ရက်နဲ့ 600ms ကြာသွားပြီး page တိုင်း နှေးသွားပါတယ်။
import { readFile } from 'node:fs/promises';
const raw = readFile('./app.json', 'utf8'); // forgot await: a Promise
const config = JSON.parse(raw);
// SyntaxError: Unexpected token 'o', "[object Promise]" is not valid JSON
async function loadDashboard(id) {
const user = await fetchUser(id); // ~300 ms
const orders = await fetchOrders(id); // ~300 ms more, yet it never used user
return { user, orders };
}ဘာကြောင့် ဒီလို ဖြစ်တာလဲ
Promise ပြန်ပေးတဲ့ function ကို ခေါ်တာက အလုပ်ကို "စ" ရုံပဲ ရှိပါတယ်၊ ရလဒ် ရဖို့ await (ဒါမှမဟုတ် .then()) နဲ့ ထုတ်ယူရပါတယ်။ await ကတော့ နောက်ထပ် line ကို အဲဒီ Promise ပြီးမှ run ခိုင်းတာမို့ await နှစ်ခု ဆက်တိုက် ရေးရင် ဒုတိယ request က ပထမ request ပြီးမှ စပါတယ်။ အလုပ်နှစ်ခုကို အရင် စလိုက်ပြီး Promise.all နဲ့ အတူ စောင့်ရင် တစ်ပြိုင်နက် run ပါတယ်။
Core concept: Promise၊ async နဲ့ await
Promise တစ်ခုက pending (မပြီးသေး) အခြေအနေကနေ စပြီး fulfilled (value နဲ့ အောင်မြင်) ဒါမှမဟုတ် rejected (error နဲ့ ကျရှုံး) ကို တစ်ကြိမ်တည်း ပြောင်းပါတယ်၊ settled ဖြစ်ပြီးရင် ထပ်မပြောင်းတော့ပါဘူး။ fs/promises၊ fetch()၊ timers/promises လို Node API အသစ်တွေက callback အစား Promise ပြန်ပေးပါတယ်။ Callback နဲ့ API အဟောင်းကို util.promisify() နဲ့ Promise ပြန်ပေးတဲ့ function အဖြစ် ပြောင်းလို့ ရပါတယ်။
async ပါတဲ့ function က အမြဲ Promise ပြန်ပေးပါတယ် — return 5 လို့ ရေးလည်း caller က Promise<5> ကို ရပြီး function ထဲမှာ throw လုပ်ရင် rejected Promise ဖြစ်ပါတယ်။ await promise က အဲဒီ async function ကိုပဲ ခဏရပ်ပြီး Promise settle ဖြစ်တဲ့အခါ ဆက် run ပါတယ်၊ fulfilled ဆို value ကို ပြန်ပေးပြီး rejected ဆို error ကို အဲဒီ line မှာ throw လုပ်ပါတယ်။ ဒါကြောင့် async code ရဲ့ error တွေကို ရိုးရိုး try/catch နဲ့ ဖမ်းလို့ ရပါတယ်။ Function ရပ်နေစဉ် event loop က timer၊ တခြား request နဲ့ callback တွေကို ဆက် run ပါတယ် — thread တစ်ခုလုံး ပိတ်မနေပါဘူး။
Promise အများကြီးကို တစ်ပြိုင်နက် စောင့်ဖို့ combinator လေးခု ရှိပါတယ်။ Promise.all က အားလုံး အောင်မြင်ရင် ရလဒ်တွေကို input အစဉ်အတိုင်း array နဲ့ ပေးပြီး တစ်ခု ကျရှုံးတာနဲ့ ချက်ချင်း reject ဖြစ်ပါတယ် (ကျန်တဲ့ အလုပ်တွေကိုတော့ မရပ်ပေးပါဘူး)။ Promise.allSettled က အားလုံး ပြီးသည်အထိ စောင့်ပြီး တစ်ခုချင်းရဲ့ status ကို ပြန်ပေးပါတယ်။ ES module file တွေမှာ top-level await ကို function မပါဘဲ သုံးလို့ရပြီး CommonJS မှာတော့ async function ထဲမှာပဲ await သုံးလို့ ရပါတယ်။
ကျန်နှစ်ခုက ပြိုင်ပွဲလိုပါ။ Promise.race က ပထမဆုံး settle ဖြစ်တဲ့ Promise ရဲ့ ရလဒ် ဒါမှမဟုတ် error ကို ယူလို့ timeout ဆောက်ဖို့ အသုံးများပါတယ် — အလုပ်နဲ့ timer ကို ပြိုင်ခိုင်းပြီး timer နိုင်ရင် error ဖြစ်ပါတယ်။ Promise.any ကတော့ ပထမဆုံး အောင်မြင်တဲ့ ရလဒ်ကို ယူပြီး အားလုံး ကျရှုံးမှသာ AggregateError နဲ့ reject ဖြစ်လို့ mirror server အများကြီးထဲက အမြန်ဆုံး ဖြေတဲ့ တစ်ခုကို ရွေးတာမျိုးမှာ သုံးပါတယ်။
| Combinator | ဘယ်အချိန် resolve/reject ဖြစ်လဲ |
|---|---|
| Promise.all | အားလုံး အောင်မြင်ရင် / တစ်ခု ကျရှုံးတာနဲ့ |
| Promise.allSettled | အားလုံး ပြီးသွားရင် (ဘယ်တော့မှ reject မဖြစ်) |
| Promise.race | ပထမဆုံး settle ဖြစ်တဲ့ တစ်ခု |
| Promise.any | ပထမဆုံး အောင်မြင်တဲ့ တစ်ခု |
- Function ခေါ်ရင် အလုပ်စပြီး Promise ရ
- await က ဒီ function ကိုပဲ ရပ်
- Event loop က တခြားအလုပ် ဆက်လုပ်
- Fulfilled → value၊ rejected → throw
အလုပ်တွေ အားလုံးကို အရင် စလိုက်ပြီးမှ စောင့်ရင် တစ်ပြိုင်နက် run ပါတယ်၊ တစ်ခုချင်း စ-စောင့် လုပ်ရင် တန်းစီ run ပါတယ်။
အထွေထွေ ပုံစံ
async function name(input) {
try {
const one = await stepThatReturnsAPromise(input); // in sequence
const [a, b] = await Promise.all([taskA(one), taskB(one)]); // together
return combine(a, b);
} catch (error) {
throw new Error('What failed, in plain words', { cause: error });
}
}
const result = await name(value); // top-level await: ES modules onlyအရင်လုပ်ရမယ့် အဆင့်ကို await နဲ့ တန်းစီပြီး တစ်ခုနဲ့တစ်ခု မမှီခိုတဲ့ အလုပ်တွေကို Promise.all နဲ့ အတူ run ပါတယ်။ catch ထဲမှာ error ကို message ရှင်းရှင်းနဲ့ ပြန် throw လုပ်ပြီး မူလ error ကို cause ထဲ သိမ်းထားပါတယ်။
Example: config file နှစ်ခုကို တစ်ပြိုင်နက် ဖတ်ခြင်း
Example က temporary folder ထဲမှာ app.json နဲ့ messages.json ကို ရေးပြီး loadConfig() နဲ့ Promise.all သုံးကာ file နှစ်ခုလုံးကို တစ်ပြိုင်နက် ဖတ်ပါတယ်။ ပထမဆုံး loadConfig() ကို await မပါဘဲ ခေါ်ပြီး Promise ပြန်လာတာကို ပြပါတယ်၊ ပြီးမှ await နဲ့ ရလဒ်ကို ယူပါတယ်။ နောက်ဆုံးမှာ မရှိတဲ့ folder ကို ဖတ်ခိုင်းပြီး error message နဲ့ မူလ error ရဲ့ code (ENOENT) ကို cause ကနေ print ထုတ်ပါတယ်။
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
const dir = await mkdtemp(path.join(tmpdir(), 'config-'));
await writeFile(path.join(dir, 'app.json'), '{"name":"Tutorial API","port":3000}');
await writeFile(path.join(dir, 'messages.json'), '{"welcome":"Mingalaba"}');
async function loadConfig(folder) {
try {
const [app, messages] = await Promise.all([
readFile(path.join(folder, 'app.json'), 'utf8'),
readFile(path.join(folder, 'messages.json'), 'utf8'),
]);
return { app: JSON.parse(app), messages: JSON.parse(messages) };
} catch (error) {
throw new Error('Could not load configuration', { cause: error });
}
}
const pending = loadConfig(dir);
console.log('loadConfig returned:', pending instanceof Promise ? 'a Promise' : 'data');
const config = await pending;
console.log(config.app.name, '-', config.messages.welcome);
try {
await loadConfig(path.join(dir, 'missing'));
} catch (error) {
console.log(error.message, '| cause:', error.cause.code);
}
await rm(dir, { recursive: true, force: true });Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Two reads at once
const [app, messages] = await Promise.all([readFile နှစ်ခုလုံး array ထဲမှာ ချက်ချင်း စပြီး Promise.all က နှစ်ခုလုံး ပြီးမှ ရလဒ်ကို input အစဉ်အတိုင်း ပြန်ပေးပါတယ်၊ ဒါကြောင့် destructuring နဲ့ နာမည်ပေးလို့ ရပါတယ်။
- Wrapping the error
throw new Error('Could not load configuration', { cause: error });Caller အတွက် နားလည်ရလွယ်တဲ့ message အသစ်နဲ့ throw လုပ်ပြီး ENOENT လို မူလ error ကို cause ထဲ ထည့်ထားလို့ debug လုပ်တဲ့အခါ အချက်အလက် မပျောက်ပါဘူး။
- Calling without await
const pending = loadConfig(dir);async function ကို await မပါဘဲ ခေါ်ရင် အလုပ်က စသွားပေမယ့် ရလာတာက data မဟုတ်ဘဲ Promise ပါ — problem section ထဲက bug ရဲ့ အကြောင်းရင်းပါ။
- Waiting for the result
const config = await pending;စပြီးသား Promise ကို နောက်မှ await လုပ်လို့ ရပါတယ်။ ဒါက တစ်ပြိုင်နက် run ခြင်းရဲ့ အခြေခံပါ — အရင်စ၊ နောက်မှ စောင့်။
- Catching the failure
console.log(error.message, '| cause:', error.cause.code);missing folder ထဲမှာ file မရှိလို့ readFile reject ဖြစ်ပြီး await က error ကို throw လုပ်ကာ try/catch က ဖမ်းပါတယ်။ cause.code ကနေ ENOENT (file မရှိ) ကို ဖတ်ပါတယ်။
loadConfig returned: a Promise
Tutorial API - Mingalaba
Could not load configuration | cause: ENOENTတန်းစီ run တာနဲ့ တစ်ပြိုင်နက် run တာ
အောက်က code မှာ 60ms ကြာတဲ့ task A နဲ့ 20ms ကြာတဲ့ task B ကို နည်းနှစ်မျိုးနဲ့ run ပါတယ်။ တန်းစီ run ရင် A ပြီးမှ B စလို့ စုစုပေါင်း 80ms လောက် ကြာပြီး "done" အစဉ်က A၊ B ပါ။ Promise.all နဲ့ run ရင် နှစ်ခုလုံး တစ်ပြိုင်နက် စလို့ 60ms လောက်ပဲ ကြာပြီး B က အရင် ပြီးပါတယ် — ဒါပေမယ့် ရလဒ် array က ['A', 'B'] input အစဉ်အတိုင်း ရှိနေဆဲပါ။
import { setTimeout as sleep } from 'node:timers/promises';
async function task(name, ms) {
await sleep(ms);
console.log('done:', name);
return name;
}
console.log('-- sequential');
await task('A', 60);
await task('B', 20);
console.log('-- concurrent');
console.log(await Promise.all([task('A', 60), task('B', 20)]));Unhandled rejection က process ကို ရပ်စေပါတယ်
Node 15 နောက်ပိုင်းမှာ ဘယ်သူမှ catch မလုပ်တဲ့ rejected Promise ရှိရင် Node က error ကို print ထုတ်ပြီး process ကို exit code 1 နဲ့ ရပ်ပါတယ်။ Promise တိုင်းကို await (try/catch နဲ့) ဒါမှမဟုတ် .catch() နဲ့ ကိုင်တွယ်ပါ။
လက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
Express route handler တစ်ခုက database ကနေ user ကို ယူ၊ order တွေ ယူ၊ recommendation service ကို ခေါ် ဆိုတဲ့ I/O အလုပ်တွေ လုပ်လေ့ ရှိပါတယ်။ User ID မှာ မူတည်တဲ့ အလုပ်နှစ်ခုကို Promise.all နဲ့ တစ်ပြိုင်နက် run လိုက်တာနဲ့ response time က တစ်ဝက်လောက် ကျသွားတတ်ပါတယ်။ Express 5 က async handler ရဲ့ rejection ကို error middleware ဆီ ပို့ပေးလို့ database ကျသွားရင်လည်း request တန်းလန်း မကျန်ဘဲ 500 response ရပါတယ်။
Dashboard လို page မှာ widget ဆယ်ခုရဲ့ data ကို service အမျိုးမျိုးကနေ ယူရရင် Promise.allSettled က အသုံးဝင်ပါတယ် — service တစ်ခု ကျသွားလည်း ကျန်တဲ့ widget ကိုးခုကို ပြပြီး ကျသွားတဲ့ widget မှာပဲ "ယာယီ မရနိုင်ပါ" လို့ ပြလို့ ရပါတယ်။ ပြင်ပ API ခေါ်တိုင်းမှာ timeout ထည့်တာကလည်း ပုံမှန် အလေ့အကျင့်ပါ၊ fetch() မှာ signal: AbortSignal.timeout(2000) လို့ ထည့်လို့ ရပါတယ်။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. forEach ထဲမှာ await သုံးတာ
files.forEach(async (f) => { await upload(f); }) က forEach က callback ပြန်ပေးတဲ့ Promise တွေကို မစောင့်လို့ upload တွေ မပြီးခင် "All uploaded" ကို print ထုတ်ပြီး error တွေလည်း ဖမ်းမမိပါဘူး။ တန်းစီချင်ရင် for...of ထဲမှာ await၊ တစ်ပြိုင်နက် ဆိုရင် await Promise.all(files.map(upload)) ကို သုံးပါ။
2. try/catch က await မပါတဲ့ Promise ကို ဖမ်းမယ်လို့ ထင်တာ
try { saveUser(data); } catch {} ဆိုရင် saveUser() က reject ဖြစ်တာ try block ပြီးသွားမှ ဖြစ်လို့ catch က ဘယ်တော့မှ မရောက်ဘဲ unhandled rejection ဖြစ်ပါတယ်။ try ထဲမှာ return await ဒါမှမဟုတ် await ကို ထည့်ပါ။
3. Promise.all ကို အဆမတန် ကြီးတဲ့ list နဲ့ သုံးတာ
URL တစ်သောင်းကို Promise.all(urls.map(fetch)) နဲ့ တစ်ခါတည်း ခေါ်ရင် connection တစ်သောင်း တစ်ပြိုင်နက် ဖွင့်ပြီး ကိုယ့် server ဒါမှမဟုတ် တစ်ဖက် API ကို ဖိအားပေးပါတယ်။ List ကို အစုလေးတွေ (ဥပမာ ၁၀ ခုစီ) ခွဲပြီး run ပါ။
Mini challenge
Mini challenge: timeout ပါတဲ့ dashboard loader
Service သုံးခုကို တစ်ပြိုင်နက် ခေါ်ပြီး တစ်ခုချင်းကို 100ms timeout ပေးကာ Promise.allSettled နဲ့ ရလဒ်အားလုံးကို အစီရင်ခံတဲ့ loader တစ်ခု ရေးပါ။
- fetchService(name, ms, shouldFail) က timers/promises ရဲ့ setTimeout နဲ့ ms စောင့်ပြီး string ပြန် ဒါမှမဟုတ် throw လုပ်ရမယ်
- withTimeout(promise, ms, label) က Promise.race နဲ့ timeout error ကို reject လုပ်ပြီး timer ကို clear လုပ်ရမယ်
- users (20ms)၊ orders (30ms၊ ကျရှုံး)၊ reports (300ms) ကို Promise.allSettled နဲ့ run ရမယ်
- ရလဒ်တစ်ခုစီကို OK ဒါမှမဟုတ် FAIL နဲ့ input အစဉ်အတိုင်း print ထုတ်ရမယ်
import { setTimeout as sleep } from 'node:timers/promises';
async function fetchService(name, ms, shouldFail = false) {
// TODO: wait ms, then throw "<name> failed" or return "<name> ok"
}
function withTimeout(promise, ms, label) {
// TODO: race the promise against a timer that rejects with
// "<label> timed out after <ms> ms"; clear the timer afterwards
}
// TODO: Promise.allSettled over users (20), orders (30, fails), reports (300)
// TODO: print "OK <value>" or "FAIL <reason.message>" for each resultရလဒ်: ရရမယ့် output: OK users ok FAIL orders failed FAIL reports timed out after 100 ms
အရိပ်အမြွက် ကြည့်ရန်
Timer ကို new Promise((_, reject) => { timer = setTimeout(...) }) နဲ့ ဆောက်ပြီး Promise.race([promise, timeout]).finally(() => clearTimeout(timer)) လို့ ပြန်ပေးပါ။ allSettled ရလဒ်တစ်ခုစီမှာ status၊ value ဒါမှမဟုတ် reason ပါပါတယ်။
အဖြေ ကြည့်ရန်
import { setTimeout as sleep } from 'node:timers/promises';
async function fetchService(name, ms, shouldFail = false) {
await sleep(ms);
if (shouldFail) throw new Error(`${name} failed`);
return `${name} ok`;
}
function withTimeout(promise, ms, label) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
const results = await Promise.allSettled([
withTimeout(fetchService('users', 20), 100, 'users'),
withTimeout(fetchService('orders', 30, true), 100, 'orders'),
withTimeout(fetchService('reports', 300), 100, 'reports'),
]);
for (const result of results) {
if (result.status === 'fulfilled') console.log('OK ', result.value);
else console.log('FAIL', result.reason.message);
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Promise က pending ကနေ fulfilled ဒါမှမဟုတ် rejected ကို တစ်ကြိမ်တည်း ပြောင်းတယ်။
- async function က အမြဲ Promise ပြန်ပြီး await က အဲဒီ function ကိုပဲ ရပ်တယ်၊ event loop ကို မပိတ်ဘူး။
- မမှီခိုတဲ့ အလုပ်တွေကို အရင် စပြီး Promise.all နဲ့ အတူ စောင့်ပါ၊ တစ်ခုချင်းစီရဲ့ ရလဒ် လိုရင် allSettled ကို သုံးပါ။
- Rejection တွေကို try/catch နဲ့ ဖမ်းပြီး { cause } နဲ့ မူလ error ကို ထိန်းထားပါ။
Discover Promises in Node.js — Node.js
Asynchronous work — Node.js