Thuta Learning
JavaScript
AdvancedProgrammingအခြေခံ

Async / Await

JavaScriptသင်ခန်းစာ 3530 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • async function ရဲ့ return value နဲ့ throw လုပ်တဲ့ error က Promise ဘယ်လို ဖြစ်သွားလဲ ရှင်းပြနိုင်ဖို့
  • await က event loop တစ်ခုလုံးကို မရပ်ဘဲ လက်ရှိ function ကိုပဲ ရပ်တယ်ဆိုတာ output နဲ့ သက်သေပြနိုင်ဖို့
  • Rejection ကို try/catch နဲ့ ဖမ်းပြီး cleanup ကို finally ထဲ ထားနိုင်ဖို့
  • for...of နဲ့ sequential၊ Promise.all နဲ့ parallel ကို ရွေးချယ်နိုင်ပြီး forEach(async ...) ထောင်ချောက်ကို ရှောင်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Async/await ကို ရိုးရိုးလေး ပြောရရင်

Async/await က Promise အသစ်တစ်မျိုး မဟုတ်ပါဘူး၊ Promise တွေကို ပိုဖတ်ရလွယ်အောင် ရေးနည်းတစ်ခုပါ။ then callback တွေ ဆင့်ကာဆင့်ကာ ချိတ်မယ့်အစား အပေါ်ကနေ အောက်ကို ဖတ်သွားလို့ရတဲ့ code ကို ရေးလို့ ရပါတယ်။ Function ရှေ့မှာ async ထည့်ပြီး Promise တစ်ခုရဲ့ ရလဒ်ကို လိုချင်တဲ့နေရာမှာ await ကို ရေးလိုက်ရုံပါပဲ။

ကော်ဖီဆိုင်မှာ မှာပြီး ကောင်တာနားမှာ စောင့်နေတာကို စဉ်းစားကြည့်ပါ။ သင်ကတော့ စောင့်နေပါတယ်၊ ဒါပေမဲ့ barista က တခြား customer တွေကို ဆက်ပြီး ဝန်ဆောင်မှု ပေးနေပါတယ်။ await ကလည်း ဒီလိုပါပဲ: async function တစ်ခုတည်းက ခဏရပ်စောင့်ပြီး JavaScript engine ကတော့ တခြား code တွေကို ဆက် run နေပါတယ်။

Problem → Why → Solution

ပြဿနာ: forEach က မစောင့်ပေးဘူး

Order သုံးခုကို save ပြီးမှ 'all saved' ကို ပြချင်တယ် ဆိုပါစို့။ forEach ထဲမှာ async callback ကို ပေးလိုက်ရင် code က ကြည့်ရတာ မှန်နေပေမဲ့ 'all saved' က save တစ်ခုမှ မပြီးခင် print ထွက်လာပါတယ်။ Save တစ်ခု fail ရင်လည်း try/catch က မမိဘဲ unhandled rejection ဖြစ်သွားပါတယ်။

foreach-trap.js
async function saveAll(orders) {
  try {
    orders.forEach(async (order) => {
      await saveOrder(order); // forEach ignores the Promise this returns
    });
    console.log("all saved"); // prints immediately
  } catch (error) {
    console.error("save failed", error); // never reached for a failed save
  }
}

ဘာကြောင့် ဒီလို ဖြစ်တာလဲ

async callback တိုင်းက Promise တစ်ခု ပြန်ပေးပါတယ်၊ ဒါပေမဲ့ forEach က callback ရဲ့ return value ကို လွှင့်ပစ်ပါတယ်။ ဒါကြောင့် saveAll ထဲမှာ ဘယ်သူမှ အဲဒီ Promise တွေကို await မလုပ်ပါဘူး။ တစ်ခုပြီးမှ တစ်ခု save ချင်ရင် for...of နဲ့ await ကို သုံးပါ၊ တစ်ပြိုင်နက် save ချင်ရင် await Promise.all(orders.map(saveOrder)) ကို သုံးပါ။

Core concept: async က Promise ပြန်ပေးပြီး await က unwrap လုပ်တယ်

Function ရှေ့မှာ async ထည့်လိုက်ရင် အဲဒီ function က Promise ကို အမြဲ ပြန်ပေးပါတယ်။ return "hi" လို့ ရေးရင် "hi" နဲ့ fulfilled ဖြစ်တဲ့ Promise ကို ရပါတယ်၊ throw new Error("x") လို့ ရေးရင် အဲဒီ error နဲ့ rejected ဖြစ်တဲ့ Promise ကို ရပါတယ်။ ဒါကြောင့် ခေါ်တဲ့သူက .then() နဲ့ ဖြစ်ဖြစ်၊ await နဲ့ ဖြစ်ဖြစ် ရလဒ်ကို ယူရပါတယ်။

await promise က Promise settle ဖြစ်တဲ့အထိ လက်ရှိ async function ကို ခဏရပ်ပါတယ်။ Fulfilled ဖြစ်ရင် value ကို expression ရဲ့ ရလဒ်အဖြစ် ပြန်ပေးပြီး rejected ဖြစ်ရင် အဲဒီ နေရာမှာပဲ reason ကို throw လုပ်ပါတယ်။ အဲဒါကြောင့် ရိုးရိုး try/catch က async error တွေကို ဖမ်းနိုင်တာပါ။ ရပ်နေတဲ့အချိန်မှာ engine က ခေါ်တဲ့သူဆီ ပြန်သွားပြီး တခြား code၊ timer နဲ့ event တွေကို ဆက် run ပါတယ်၊ thread ကို block မလုပ်ပါဘူး။

await ကို async function ထဲမှာပဲ သုံးလို့ရပါတယ်။ ချွင်းချက်က ES module ရဲ့ top level နဲ့ browser DevTools console ပါ။ CommonJS file ရဲ့ top level မှာ await ရေးရင် SyntaxError ရပါတယ်၊ ဒါကြောင့် async function main() { ... } ထဲ ထည့်ပြီး main() ကို ခေါ်တာက နေရာတိုင်းမှာ အလုပ်လုပ်ပါတယ်။

အရေးကြီးဆုံး performance အချက်ကတော့ await တစ်ခုချင်းစီက စောင့်ချိန်တွေကို ပေါင်းသွားစေတာပါ။ နောက်တစ်ဆင့်က ရှေ့ကရလဒ်ကို လိုအပ်ရင် sequential က မှန်ပါတယ်။ မမှီခိုတဲ့ အလုပ်တွေကိုတော့ အရင်စလိုက်ပြီး Promise.all နဲ့ အတူတူ စောင့်ပါ၊ အဲဒီအခါ စုစုပေါင်းချိန်က အကြာဆုံး တစ်ခုလောက်ပဲ ကြာပါတယ်။

Error တွေက ခေါ်တဲ့သူဆီ Promise rejection အနေနဲ့ ပြန်တက်သွားပါတယ်။ async function တစ်ခုက try/catch မပါရင် သူ့ကို await လုပ်တဲ့ function ရဲ့ try/catch က ဖမ်းနိုင်ပါတယ်၊ ဒါပေမဲ့ chain ရဲ့ အပေါ်ဆုံးမှာ main().catch(handleError) လို တစ်နေရာရာက ကိုင်တွယ်ပေးရပါမယ်။ ဘယ်သူမှ မကိုင်တွယ်ရင် unhandled rejection ဖြစ်ပါတယ်။

ပုံစံရလဒ်
for (const x of xs) await work(x)တစ်ခုပြီးမှ တစ်ခု၊ အချိန်တွေ ပေါင်း
await Promise.all(xs.map(work))တစ်ပြိုင်နက်၊ ပထမ error မှာ reject
xs.forEach(async (x) => await work(x))ဘယ်သူမှ မစောင့်၊ error တွေ ပျောက်
await ကို 'ဒီ function တစ်ခုတည်း pause' ခလုတ်လို မြင်ပါ
  1. async function ကို ခေါ် → Promise ချက်ချင်းရ
  2. await မှာ ဒီ function ခဏရပ်
  3. Engine က တခြား code ဆက် run
  4. Fulfill → value၊ reject → throw

await တစ်ခုချင်းစီက 'စောင့်' လို့ ပြောတာပါ။ ကိုယ်တကယ် စောင့်ဖို့ လိုသလား၊ ဒါမှမဟုတ် အလုပ်တွေကို အတူတူ စလို့ရသလား အမြဲ မေးပါ။

အထွေထွေ ပုံစံ

javascript
async function name(params) {
  try {
    const a = await stepOne(params);       // dependent steps: in order
    const [b, c] = await Promise.all([jobB(a), jobC(a)]); // independent
    return combine(b, c);                  // fulfils the returned Promise
  } catch (error) {
    // any rejected await above lands here
  } finally {
    // cleanup that must always run
  }
}

async function ထဲမှာ ရှေ့ကရလဒ်ကို မှီခိုတဲ့ အဆင့်တွေကို တစ်ခုချင်း await ပြီး မမှီခိုတဲ့ အလုပ်တွေကိုတော့ Promise.all နဲ့ အတူတူ await ပါ။ Rejection တွေကို try/catch က ဖမ်းပြီး finally က အမြဲ run ပါတယ်။

Worked example: await က ဘာကို ရပ်ပြီး ဘာကို မရပ်ဘူးလဲ

asyncCall က two-second timer ကို စောင့်ပြီးမှ string တစ်ခု return လုပ်ပါတယ်၊ script ရဲ့ အဆုံးမှာလည်း log တစ်ကြောင်း ရှိပါတယ်။ Output အစီအစဉ်ကို ကြည့်ပါ: script ရဲ့ နောက်ဆုံး line က timer မပြီးခင် ထွက်လာပါတယ်၊ await က asyncCall ကိုပဲ ရပ်ထားလို့ပါ။

async-await.js
function resolveAfter2Seconds() {
  return new Promise((resolve) => {
    setTimeout(() => resolve("resolved"), 2000);
  });
}

async function asyncCall() {
  console.log("calling");
  const result = await resolveAfter2Seconds(); // pauses asyncCall only
  console.log(result);
  return "asyncCall finished";
}

asyncCall().then((message) => console.log(message));
console.log("the rest of the script keeps running");

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. A Promise-returning helpersetTimeout(() => resolve("resolved"), 2000);

    resolveAfter2Seconds က Promise ကို ချက်ချင်း ပြန်ပေးပြီး နှစ်စက္ကန့်ကြာမှ "resolved" နဲ့ fulfill လုပ်ပါတယ်။ ဒါက network request တစ်ခုရဲ့ ကိုယ်စား ရပ်တည်နေတာပါ။

  2. Pause this functionconst result = await resolveAfter2Seconds(); // pauses asyncCall only

    asyncCall က ဒီနေရာမှာ ခဏရပ်ပြီး ခေါ်တဲ့သူဆီ pending Promise ကို ပြန်ပေးပါတယ်။ နှစ်စက္ကန့်ကြာမှ result ထဲ "resolved" ရောက်လာပြီး နောက် line ကနေ ဆက် run ပါတယ်။

  3. Return fulfils the Promisereturn "asyncCall finished";

    async function ထဲက return က asyncCall() ပြန်ပေးခဲ့တဲ့ Promise ကို ဒီ string နဲ့ fulfill လုပ်ပါတယ်။

  4. The caller keeps goingconsole.log("the rest of the script keeps running");

    asyncCall() က await မှာ ရပ်သွားတာနဲ့ ဒီ line က ချက်ချင်း run ပါတယ်။ ဒါကြောင့် output ရဲ့ ဒုတိယ line ဖြစ်နေတာပါ။

You should see
calling
the rest of the script keeps running
resolved
asyncCall finished

try/catch/finally နဲ့ error နဲ့ cleanup

Rejected Promise ကို await လုပ်ရင် အဲဒီ line မှာ throw ဖြစ်တဲ့အတွက် synchronous code မှာ သုံးနေကျ try/catch/finally ကို တိုက်ရိုက် သုံးလို့ ရပါတယ်။ အောက်က show function က id မှန်ရင် user ကို ပြပြီး id မှားရင် error ကို ပြပါတယ်။ နှစ်မျိုးလုံးမှာ finally က spinner ကို ပိတ်ပါတယ်။

try-catch-finally.js
const wait = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function loadUserOrThrow(id) {
  if (id <= 0) throw new Error(`invalid id ${id}`); // becomes a rejection
  return wait(10, { id, name: `user-${id}` });
}

async function show(id) {
  console.log(`loading ${id}...`);
  try {
    const user = await loadUserOrThrow(id);
    console.log("loaded", user.name);
  } catch (error) {
    console.log("failed:", error.message);
  } finally {
    console.log(`spinner off for ${id}`);
  }
}

async function main() {
  await show(3); // loading 3... / loaded user-3 / spinner off for 3
  await show(-1); // loading -1... / failed: invalid id -1 / spinner off for -1
}

main();

throw လည်း rejection ဖြစ်သွားတယ်

loadUserOrThrow က async ဖြစ်တဲ့အတွက် သူ့ထဲက throw က ခေါ်တဲ့သူဆီ synchronous exception အဖြစ် မရောက်ပါဘူး၊ rejected Promise အဖြစ် ရောက်ပါတယ်။ show က အဲဒါကို await လုပ်ထားလို့ catch block က ဖမ်းနိုင်တာပါ။ main ထဲမှာ show ကို await လုပ်ထားတဲ့အတွက် 3 ရဲ့ line သုံးကြောင်းက -1 ရဲ့ line တွေ မစခင် ပြီးသွားပါတယ်။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ async/await

Express နဲ့ Fastify route handler တွေ၊ React data loader တွေ၊ CLI script တွေ စတဲ့ ယနေ့ JavaScript code အများစုကို async/await နဲ့ ရေးကြပါတယ်။ ပုံစံတွေက အမြဲ ပြန်ပေါ်လာပါတယ်: မှီခိုတဲ့ အဆင့်တွေကို အစဉ်လိုက်၊ မမှီခိုတဲ့ request တွေကို တစ်ပြိုင်နက်၊ cleanup ကို finally ထဲမှာ ထားတာပါ။

  • Product page တစ်ခုက product၊ review နဲ့ stock ကို တစ်ပြိုင်နက် စပြီး await Promise.all နဲ့ စောင့်ပါတယ်။ Sequential ဆိုရင် 300 ms စီ ကြာတဲ့ request သုံးခုက 900 ms ခန့် ကြာမှာဖြစ်ပြီး parallel ဆိုရင် 300 ms ခန့်ပဲ ကြာပါတယ်။
  • Checkout flow မှာတော့ order ဖန်တီးပြီးမှ ငွေချေ၊ ငွေချေပြီးမှ email ပို့ရတဲ့အတွက် တစ်ဆင့်ချင်း await လုပ်တာ မှန်ပါတယ်၊ ရှေ့ကရလဒ်ကို နောက်တစ်ဆင့်က လိုလို့ပါ။
  • Data import script က row ထောင်ချီကို for...of နဲ့ batch လိုက် await လုပ်ပြီး database ကို request အများကြီး တစ်ပြိုင်နက် မပို့မိအောင် ထိန်းပါတယ်။

အမှားများ

Async/await နဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

forEach ထဲမှာ async callback သုံးခြင်း

forEach က callback ပြန်ပေးတဲ့ Promise ကို လျစ်လျူရှုလို့ loop ပြီးတာနဲ့ အလုပ်တွေ မပြီးသေးပါဘူး၊ error တွေလည်း try/catch ကို ကျော်သွားပါတယ်။ Sequential အတွက် for...of၊ parallel အတွက် Promise.all(items.map(...)) ကို သုံးပါ။

မမှီခိုတဲ့ အလုပ်တွေကို တစ်ခုချင်း await ခြင်း

const a = await getA(); const b = await getB(); မှာ getB က getA ကို မလိုအပ်ရင် အချိန်ကို အလကား နှစ်ဆ ဖြုန်းနေတာပါ။ const [a, b] = await Promise.all([getA(), getB()]) လို့ ရေးပါ။

await မေ့ခြင်း

const user = getUser(id); လို့ await မပါဘဲ ရေးရင် user က Promise ဖြစ်နေပြီး user.name က undefined ဖြစ်ပါတယ်။ Error ကလည်း try/catch ထဲမှာ မဖမ်းမိပါဘူး။ Promise ပြန်ပေးတဲ့ function ကို ခေါ်တိုင်း await လုပ်မလား၊ return ပြန်ပေးမလား ဆုံးဖြတ်ပါ။

Best Practices

Best practices

  • await မရေးခင် 'ဒီအဆင့်က ရှေ့ကရလဒ်ကို တကယ် လိုအပ်သလား' လို့ မေးပါ။ မလိုရင် အလုပ်တွေကို အတူတူ စပါ။
  • try/catch ကို error ကို တကယ် ကိုင်တွယ်နိုင်တဲ့နေရာ (message ပြမယ်၊ fallback သုံးမယ်) မှာပဲ ထားပါ၊ await တိုင်းကို wrap မလုပ်ပါနဲ့။
  • Loading flag ပိတ်တာ၊ lock လွှတ်တာလို cleanup ကို finally ထဲ ထားပါ၊ catch ထဲမှာ return လုပ်ခဲ့ရင်တောင် run ပါတယ်။
  • Script ရဲ့ entry point ကို main().catch(...) နဲ့ အဆုံးသတ်ပြီး ဘယ် rejection မှ မကိုင်တွယ်ဘဲ မကျန်ခဲ့အောင် လုပ်ပါ။

Mini challenge

Mini challenge: sequential နဲ့ parallel loader

အတုလုပ်ထားတဲ့ fetchUser ကို သုံးပြီး user list ကို load လုပ်တဲ့ နည်းနှစ်မျိုး ရေးပါ။ တစ်ပြိုင်နက် run နေတဲ့ request အရေအတွက် အများဆုံး (peak) ကို မှတ်ထားပြီး sequential က 1၊ parallel က 3 ဖြစ်ကြောင်း ပြပါ။ ui.loading ကို success ဖြစ်ဖြစ် error ဖြစ်ဖြစ် false ပြန်ဖြစ်အောင် finally နဲ့ ထိန်းပါ။

  • fetchUser က မသိတဲ့ id အတွက် Error throw လုပ်ပြီး active/peak counter ကို update လုပ်ရမယ်
  • loadSequential က for...of နဲ့ await ကို သုံးရမယ် (forEach မသုံးရ)
  • loadParallel က Promise.all နဲ့ map ကို သုံးရမယ်
  • run က try/catch/finally နဲ့ ui.loading ကို အမြဲ false ပြန်ထားရမယ်
loaders.js
const delays = { 1: 30, 2: 10, 3: 20 }; // fake response time per user id
let active = 0; // requests in flight right now
let peak = 0; // the most requests that were ever in flight together

async function fetchUser(id) {
  // TODO: throw new Error(`user ${id} not found`) when id is not in delays
  // TODO: active += 1, update peak, wait delays[id] ms, active -= 1
  // TODO: return { id, name: `user-${id}` }
}

async function loadSequential(ids) {
  // TODO: for...of + await, collect users in order
}

function loadParallel(ids) {
  // TODO: start every request at once and wait for all of them
}

const ui = { loading: false };

async function run(label, loader, ids) {
  // TODO: set ui.loading, reset peak, try/catch/finally, print names and peak
}

// TODO: in an async main(), run sequential [1, 2, 3], parallel [1, 2, 3],
// and parallel [2, 9] (the last one should report an error)

ရလဒ်: sequential: user-1, user-2, user-3 (peak 1)၊ parallel: user-1, user-2, user-3 (peak 3)၊ parallel: error: user 9 not found ကို ထုတ်ပြီး တစ်ခုချင်းစီရဲ့ နောက်မှာ "loading is now false" line ပါရပါမယ်။

အရိပ်အမြွက် ကြည့်ရန်

Timer ကို await လုပ်ဖို့ await new Promise((resolve) => setTimeout(resolve, ms)) ကို သုံးပါ။ main() ထဲမှာ run တစ်ခုချင်းစီကို await လုပ်မှ output line တွေ ရောနှောမသွားပါဘူး။

အဖြေ ကြည့်ရန်
loaders.js
const delays = { 1: 30, 2: 10, 3: 20 }; // fake response time per user id
let active = 0; // requests in flight right now
let peak = 0; // the most requests that were ever in flight together

async function fetchUser(id) {
  if (!(id in delays)) throw new Error(`user ${id} not found`);
  active += 1;
  peak = Math.max(peak, active);
  await new Promise((resolve) => setTimeout(resolve, delays[id]));
  active -= 1;
  return { id, name: `user-${id}` };
}

async function loadSequential(ids) {
  const users = [];
  for (const id of ids) {
    users.push(await fetchUser(id)); // waits for each one before the next
  }
  return users;
}

function loadParallel(ids) {
  return Promise.all(ids.map((id) => fetchUser(id))); // all start at once
}

const ui = { loading: false };

async function run(label, loader, ids) {
  ui.loading = true;
  peak = 0;
  try {
    const users = await loader(ids);
    console.log(label, users.map((u) => u.name).join(", "), `(peak ${peak})`);
  } catch (error) {
    console.log(label, "error:", error.message);
  } finally {
    ui.loading = false;
  }
  console.log(label, "loading is now", ui.loading);
}

async function main() {
  await run("sequential:", loadSequential, [1, 2, 3]);
  await run("parallel:", loadParallel, [1, 2, 3]);
  await run("parallel:", loadParallel, [2, 9]);
}

main();

Quick Quiz 1 / 3

async function f() { return 5; } ရှိတယ်ဆိုရင် console.log(f()) က ဘာကို print ထုတ်မလဲ?

Quick Quiz 2 / 3

getA() နဲ့ getB() က 1 စက္ကန့်စီ ကြာပြီး တစ်ခုနဲ့တစ်ခု မမှီခိုပါဘူး။ const a = await getA(); const b = await getB(); က ဘယ်လောက်ကြာမလဲ?

Quick Quiz 3 / 3

async function ထဲမှာ items.forEach(async (i) => { await save(i); }) ပြီးနောက် console.log("done") ရေးထားတယ်။ ဘာဖြစ်မလဲ?

မှတ်ထားရမယ့် အချက်များ

  • async function က Promise ကို အမြဲ ပြန်ပေးပြီး return က fulfill၊ throw က reject လုပ်ပါတယ်။
  • await က လက်ရှိ async function ကိုပဲ ရပ်ပြီး engine က တခြား code ကို ဆက် run ပါတယ်။
  • Rejected await က throw ဖြစ်လို့ try/catch/finally နဲ့ ကိုင်တွယ်နိုင်ပါတယ်။
  • မှီခိုတဲ့ အဆင့်တွေကို အစဉ်လိုက် await ပြီး မမှီခိုတဲ့ အလုပ်တွေကို Promise.all နဲ့ အတူတူ await ပါ၊ forEach(async ...) ကို ရှောင်ပါ။

MDN — Asynchronous JavaScript — MDN Web Docs

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Async / Await | Thuta Learning