Thuta Learning
ရှာဖွေရန်
IntermediateWeb Developmentbeginner

Asynchronous Node.js with Promises and async/await

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

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

  • Promise ကို await လုပ်ရန်
  • Sequential နှင့် concurrent work ခွဲရန်
  • Async error ကို handle လုပ်ရန်

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

Node.js သည် I/O လုပ်ဆောင်မှုများကိုစောင့်နေချိန် event loop ကိုမပိတ်စေရန် asynchronous APIs သုံးသည်။ async function က Promise ပြန်ပေးပြီး await က Promise settled ဖြစ်သည်အထိ function ကိုသာခဏရပ်သည်။ Independent requests များကို Promise.all ဖြင့်တပြိုင်နက်စနိုင်သည်။

javascript
import { readFile } from 'node:fs/promises'

async function loadConfig() {
  try {
    const [app, messages] = await Promise.all([
      readFile('./app.json', 'utf8'),
      readFile('./messages.json', 'utf8')
    ])
    return { app: JSON.parse(app), messages: JSON.parse(messages) }
  } catch (error) {
    throw new Error('Could not load configuration', { cause: error })
  }
}

const config = await loadConfig()
console.log(config.app.name)
You should see
Tutorial API

လက်တွေ့စမ်းကြည့်ရန်

JSON files နှစ်ခုကို sequential နှင့် Promise.all နှစ်မျိုးဖြင့်ဖတ်ပြီး execution time ကိုနှိုင်းယှဉ်ပါ။

Discover Promises in Node.jsNode.js

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • await မပါဘဲ Promise value ကိုတိုက်ရိုက်သုံးခြင်း
  • Independent tasks များကိုအကြောင်းမရှိဘဲ sequential await လုပ်ခြင်း
  • Rejected promise ကိုမကိုင်တွယ်ခြင်း

လေ့ကျင့်ခန်း

JSON files နှစ်ခုကို sequential နှင့် Promise.all နှစ်မျိုးဖြင့်ဖတ်ပြီး execution time ကိုနှိုင်းယှဉ်ပါ။

You'll know it worked when: Tutorial API

Asynchronous Node.js with Promises and async/await | Thuta Learning