紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS await 運算子:等待 Promise 結果與錯誤處理的用法

JS await 運算子:等待 Promise 結果與錯誤處理的用法 特色圖片

JS await 運算子(await operator)用來等待 Promise 完成並取得它的結果。依 MDN 的說明,await 會暫停外層 async 函式的執行,直到 Promise 完成(fulfilled)或被拒絕(rejected);完成時,整個 await 運算式的值就是 Promise 的完成值。

function resolveAfter(x, ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(x);
    }, ms);
  });
}

async function f1() {
  const x = await resolveAfter(10, 200);
  console.log(x);   // 10
}

f1();
console.log("f1 已呼叫,這行先印出");
// f1 已呼叫,這行先印出
// 10

await 暫停的只是 f1 自己,呼叫 f1() 的外層程式不會停下來,所以「這行先印出」會比 10 早出現。async 函式的寫法與回傳值,可前往 async function 的語法文觀看;Promise 的狀態與建構子,可前往 Promise 的語法文觀看。

await 的語法與可用位置

語法只有一行,await 後面接一個運算式:

await expression

依 MDN 的說明:

  • 運算元(operand):優先順序為 14(前置運算子)以上的運算式,值可以是 Promise、thenable 物件,或任何其他值。
  • 回傳值:Promise 或 thenable 的完成值;如果運算式不是 thenable,就是運算式本身的值。
  • 例外:Promise 或 thenable 被拒絕時,丟出被拒絕的原因(rejection reason)。

await 只能寫在 async 函式裡,或模組(module)的最上層。MDN 說明,await 不會阻塞主執行緒,只會延後真正依賴結果的程式碼,也就是 await 之後的那些敘述。

哪些地方不能用 await

在一般函式、同步的回呼函式,或一般 script 的最上層寫 await,會得到 SyntaxError。最常見的情況是在 forEach 的同步回呼裡用 await:

try {
  new Function("const urls = [1]; urls.forEach((url) => { await Promise.resolve(url); });");
} catch (e) {
  console.log(e.name, "|", e.message);
}
// SyntaxError | await is only valid in async functions and the top level bodies of modules

錯誤訊息的文字依引擎而異,上面是 Node.js v22.20.0 的輸出;MDN 列出的 Firefox 訊息是 await is only valid in async functions, async generators and modules,Safari 則是 Unexpected identifier。

解法是把回呼函式改成 async。MDN 的寫法是搭配 Promise.all(),讓每個回呼各自 await:

function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

const urls = [1, 2, 3];
const results = await Promise.all(
  urls.map(async (url) => {
    await delay(10);
    return url * 2;
  }),
);
console.log(results);   // [ 2, 4, 6 ]

上面最外層的 await 是頂層 await,要在模組裡才能執行,下面會說明。

await 後面接不同的值

MDN 說明,await 後面的運算式會依照 Promise.resolve() 的方式處理,一律先轉成原生 Promise 再等待:

運算式的類型處理方式
原生 Promise直接使用,不呼叫 then()
thenable 物件(含非原生 Promise、polyfill、proxy、子類別)呼叫物件的 then() 方法,包成一個新的原生 Promise
其他值包成一個已完成的 Promise

thenable 是有可呼叫的 then 方法的物件,處理方式和真正的 Promise 一樣,可以完成,也可以被拒絕:

async function f2() {
  const thenable = {
    then(resolve) {
      resolve("resolved!");
    },
  };
  console.log(await thenable);   // resolved!
}
await f2();

async function f2b() {
  const thenable = {
    then(_, reject) {
      reject(new Error("rejected!"));
    },
  };
  try {
    await thenable;
  } catch (e) {
    console.log(e.message);   // rejected!
  }
}
await f2b();

後面接的不是 Promise 時,await 會把值包成已完成的 Promise 再等待。只要值沒有可呼叫的 then 屬性,它的身分(identity)不會改變:

async function f3() {
  const y = await 20;
  console.log(y);   // 20

  const obj = {};
  console.log((await obj) === obj);   // true
}
await f3();

await 之後的程式何時繼續

遇到 await 時,被等待的運算式會先執行,依賴它的後續程式碼則暫停,控制權交回呼叫端。MDN 說明,即使被等待的 Promise 早就完成,或值根本不是 Promise,async 函式也要等到下一個 tick 才會繼續;這段時間呼叫端會先往下跑。

下面是 MDN 的對照。函式裡沒有 await 時,三個敘述在同一個 tick 內執行完,兩次呼叫依序跑完:

async function foo(name) {
  console.log(name, "start");
  console.log(name, "middle");
  console.log(name, "end");
}

foo("First");
foo("Second");
// First start
// First middle
// First end
// Second start
// Second middle
// Second end

只要中間有一個 await,後面的敘述就會被排進微任務(microtask),兩次呼叫的輸出因此交錯:

async function foo(name) {
  console.log(name, "start");
  await console.log(name, "middle");
  console.log(name, "end");
}

foo("First");
foo("Second");
// First start
// First middle
// Second start
// Second middle
// First end
// Second end

MDN 提醒,每個 await 都會多出一個微任務,可能讓程式變慢,也可能製造不必要的競賽條件(race condition)。所以只有需要把 Promise 解開成值的時候才用 await。

await 和 queueMicrotask() 排進的都是微任務,依排入的順序執行。下面的輸出可以看到兩者交錯:

let i = 0;
queueMicrotask(function test() {
  i++;
  console.log("microtask", i);
  if (i < 3) {
    queueMicrotask(test);
  }
});

(async () => {
  console.log("async function start");
  for (let i = 1; i < 3; i++) {
    await null;
    console.log("async function resume", i);
  }
  await null;
  console.log("async function end");
})();

queueMicrotask(() => {
  console.log("queueMicrotask() after calling async function");
});

console.log("script sync part end");
// async function start
// script sync part end
// microtask 1
// async function resume 1
// queueMicrotask() after calling async function
// microtask 2
// async function resume 2
// microtask 3
// async function end

await 的錯誤處理

await 的 Promise 被拒絕時,會把拒絕的原因丟出來,所以可以用 try...catch 接住:

async function f4() {
  try {
    const z = await Promise.reject(new Error("rejected!"));
  } catch (e) {
    console.log(e.message);   // rejected!
  }
}
await f4();

另一種寫法是在 await 之前先接上 catch(),被拒絕時改用後備值:

function promisedFunction() {
  return new Promise((resolve, reject) => {
    reject(new Error("failed"));
  });
}

const response = await promisedFunction().catch((err) => {
  console.log("錯誤:", err.message);
  return "default response";
});
console.log(response);
// 錯誤: failed
// default response

MDN 說明,這種寫法的前提是函式不會同步丟出錯誤,而是回傳被拒絕的 Promise。如果函式在回傳 Promise 之前就同步 throw,catch() 根本來不及接上,這時要用 try...catch:

function syncThrower() {
  throw new Error("sync error");
}

try {
  await syncThrower().catch(() => "fallback");
} catch (e) {
  console.log("try...catch 接到:", e.message);
}
// try...catch 接到: sync error

catch() 方法的完整用法,可前往 Promise.catch 的語法文觀看。

多個 await:依序執行還是並行

連續寫兩個 await,第二個要等第一個完成才會開始。兩件事互不相干時,可以先各自建立 Promise,再用 Promise.all() 一起等。依 MDN 的說明,Promise.all() 在所有 Promise 都完成時,以依傳入順序排列的結果陣列完成;只要有任何一個被拒絕,就立刻以第一個被拒絕的原因拒絕。

function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

let t = Date.now();
const a1 = await delay(200, "A");
const b1 = await delay(200, "B");
console.log("依序:", a1, b1, Math.round((Date.now() - t) / 100) * 100, "ms");
// 依序: A B 400 ms

t = Date.now();
const pa = delay(200, "A");
const pb = delay(200, "B");
const [a2, b2] = await Promise.all([pa, pb]);
console.log("並行:", a2, b2, Math.round((Date.now() - t) / 100) * 100, "ms");
// 並行: A B 200 ms

耗時依執行環境略有差異,上面的毫秒數已四捨五入到百位。Promise.all 的詳細行為,可前往 Promise.all 的語法文觀看。

return await 與錯誤堆疊

在 async 函式裡直接回傳 Promise 時,有人會省略 await。MDN 指出,如果那個 Promise 之後才被拒絕,錯誤堆疊(stack trace)裡就不會出現這個呼叫端函式:

async function lastAsyncTask() {
  await null;
  throw new Error("failed");
}

async function noAwait() {
  return lastAsyncTask();
}

async function withAwait() {
  return await lastAsyncTask();
}

try { await noAwait(); } catch (e) { console.log(e.stack); }
// Error: failed
//     at lastAsyncTask

try { await withAwait(); } catch (e) { console.log(e.stack); }
// Error: failed
//     at lastAsyncTask
//     at async withAwait

上面省略了各行括號內的檔案路徑。用 return await 把 Promise 解開,例外會丟進目前這個函式,堆疊就會多出 at async withAwait。MDN 另外說明,因為規格與引擎對原生 Promise 做了最佳化,return await promise 至少和 return promise 一樣快,所以除了風格考量,return await 幾乎都比較好。

模組最上層的 await(頂層 await)

在模組裡,await 可以直接寫在最上層,不必包在 async 函式裡。MDN 說明,如果一個模組有子模組使用 await,它要等子模組執行完才會跑,同層不相依的模組則不會被阻塞。

// config.mjs
const config = await Promise.resolve({ name: "demo" });
console.log(config.name);   // demo
export default config;

在瀏覽器裡,script 要加上 type="module" 才算模組;依 Node.js 文件,副檔名是 .mjs 的檔案一定當作 ES module 載入,.js 檔則要看最近的 package.json 有沒有設定 "type": "module"。一般 script 或 CommonJS 檔案的最上層寫 await,會得到 SyntaxError:

// tmp.cjs
const x = await Promise.resolve(1);
// SyntaxError: await is only valid in async functions and the top level bodies of modules

MDN 也提醒,頂層 await 不是沒有代價:它表示模組圖(module graph)有一部分只能非同步求值。模組語法與動態 import() 的細節,可參考〈ES Modules 是什麼?JavaScript import/export 模組語法與 CommonJS 的差異〉。

重點整理

  1. await 解開 Promise:暫停外層 async 函式,取得完成值;被拒絕就丟出拒絕原因。
  2. 只能寫在 async 函式或模組最上層:同步回呼函式、一般函式與一般 script 最上層會得到 SyntaxError。
  3. 後面接任何值都可以:原生 Promise 直接用,thenable 呼叫 then(),其他值包成已完成的 Promise。
  4. 之後的程式至少要等一個微任務:即使 Promise 早已完成,呼叫端也會先繼續執行。
  5. 錯誤用 try...catch 處理:或在 await 前接 catch() 給後備值,但同步丟出的錯誤只能用 try...catch。
  6. 互不相干的工作用 Promise.all():連續的 await 會依序等待。
  7. return await 讓錯誤堆疊保留呼叫端:MDN 說它至少和 return promise 一樣快。

支援版本

依 MDN 瀏覽器相容性資料(browser-compat-data 8.1.10,查詢日期 2026-11-24):

環境await頂層 await
Chrome5589
Edge1489
Firefox5289
Safari10.115(部分支援),27 起完整支援
Node.js7.6.014.8.0(不支援 CommonJS 模組)

Deno 從 1.0 開始支援兩者,Internet Explorer 不支援 await。Safari 15 到 26.6 的限制是:多個模組同時匯入含有頂層 await 的模組時不支援。MDN 把 await 標為 Baseline Widely available,自 2017 年 3 月起各主流瀏覽器都支援。

補充說明:範例在 Node.js v22.20.0 執行,其中最上層使用 await 的範例存成 .mjs 檔;多數範例來自 MDN 的 await 頁面,forEach 回呼與頂層 await 的範例是依 MDN 說明另外撰寫的示範。

參考資料與延伸閱讀

發佈留言