Skip to content

建立 2026-09-12 更新 2026-09-12

非同步

讀檔、等網路、查資料都要花時間。若程式一路傻等,同一個時間就做不了別的請求。Node.js 的做法是:遇到等待就先登記「做完再通知我」,中間可以去處理別的事。新程式用 async / await 來寫這件事。

為什麼需要 await

import { readFile } from "node:fs/promises";

const text = await readFile("package.json", "utf8");
console.log(text.slice(0, 80));

readFile 不會立刻給你字串,而是給一個 Promise(承諾稍後會有結果)。加上 await,程式會在這裡等到讀完再往下走。

忘了 await 時,你拿到的不是檔案內容,而是「還沒完成的 Promise」。

包在 async 函式裡

await 只能寫在 async 函式裡,或(有 "type": "module" 時)寫在檔案最外層。一般函式裡要等結果,就把函式改成 async function

async function loadTitle() {
  const text = await readFile("package.json", "utf8");
  const data = JSON.parse(text);
  return data.name;
}

const name = await loadTitle();
console.log(name);

錯誤怎麼接

檔案不存在、權限不足時,await readFile 會丟出錯誤。用 try / catch 接住,程式才不會直接中止:

try {
  const text = await readFile("missing.txt", "utf8");
  console.log(text);
} catch (error) {
  console.error("讀檔失敗:", error.message);
}

先不必深挖的部分

回呼(callback)與 .then() 會在舊教材出現,能讀懂即可。新程式優先寫 async / await。串流、並行 Promise.all 等主線穩了再學。

總結

I/O 幾乎都是非同步。記得 await,並用 try / catch 接失敗。這一個觀念,就能讀懂大多數 Node.js 範例。