မှတ်ချက်။ AI ပြောတိုင်းအမှန်မဟုတ်ပါဘူး၊ တခါတလေသူကအမှားတွေပါပြောတက်ပါတယ်။ ကိုယ်ပိုင်စဥ်းစားဆင်ခြင်ဆုံးဖြတ်ပါ။
NodeJS က Promise ကိုသေချာရှင်းပြပေးပါ မြင်သာတဲ့ဥပမာလေးပါထည့်ပေးပါ။ ကုဒ်နဲ့တခါထဲရှင်းပြရင်ပိုသဘောကျပါတယ်။
NodeJS မှာ Promise ဆိုတာ asynchronous သဘောသဘာဝရှိတဲ့ လုပ်ဆောင်ချက်တွေကို စီမံခန့်ခွဲဖို့အတွက် အသုံးပြုတဲ့ object တစ်ခုဖြစ်ပါတယ်။ Promise က အဓိကအားဖြင့် pending, fulfilled, နဲ့ rejected ဆိုတဲ့ အခြေအနေ သုံးမျိုးရှိပါတယ်။
ဥပမာတစ်ခုနဲ့ရှင်းပြရရင် file ဖတ်တဲ့ လုပ်ဆောင်ချက်ကို Promise နဲ့ရေးသားပုံကို ကြည့်ရအောင်:
const fs = require('fs').promises; function readFileContent(filePath) { return fs.readFile(filePath, 'utf8') .then(content => { console.log('File content:', content); return content; }) .catch(error => { console.error('Error reading file:', error); throw error; }); } // Promise ကို အသုံးပြုခြင်း readFileContent('example.txt') .then(content => { console.log('File reading completed successfully'); }) .catch(error => { console.log('An error occurred while reading the file'); });
function readFileContent(filePath) { return fs.readFile(filePath, 'utf8') .then(content => { console.log('File content:', content); return content; }) .catch(error => { console.error('Error reading file:', error); throw error; }); }
// Promise ကို အသုံးပြုခြင်း readFileContent('example.txt') .then(content => { console.log('File reading completed successfully'); }) .catch(error => { console.log('An error occurred while reading the file'); });
ဒီဥပမာမှာ:
readFileContent
fs.readFile
.then()
.catch()
Promise တွေကို async/await syntax နဲ့လည်း အသုံးပြုနိုင်ပါတယ်။ ဥပမာ:
async function readFileAsync(filePath) { try { const content = await fs.readFile(filePath, 'utf8'); console.log('File content:', content); return content; } catch (error) { console.error('Error reading file:', error); throw error; } } // async/await ကို အသုံးပြုခြင်း async function main() { try { const content = await readFileAsync('example.txt'); console.log('File reading completed successfully'); } catch (error) { console.log('An error occurred while reading the file'); } } main();
// async/await ကို အသုံးပြုခြင်း async function main() { try { const content = await readFileAsync('example.txt'); console.log('File reading completed successfully'); } catch (error) { console.log('An error occurred while reading the file'); } }
main();
ဒီနည်းက Promise ကို ပိုပြီးရိုးရှင်းတဲ့ပုံစံနဲ့ အသုံးပြုနိုင်စေပါတယ်။ အထူးသဖြင့် Promise chain တွေများလာတဲ့အခါ ပိုပြီးဖတ်ရလွယ်ကူစေပါတယ်။