首頁 >web前端 >js教程 >為什麼 JavaScript 中會出現「await 僅在非同步函數中有效」?

為什麼 JavaScript 中會出現「await 僅在非同步函數中有效」?

Linda Hamilton
Linda Hamilton原創
2025-01-03 19:16:41543瀏覽

Why Does

「await 僅在非同步函數中有效」錯誤

在 JavaScript 中,await 關鍵字僅在非同步函數中有效。當嘗試在非非同步函數中使用await時,會發生此錯誤。

請考慮以下程式碼片段:

// lib/helper.js
var myfunction = async function (x, y) {
  return [x, y];
};
exports.myfunction = myfunction;

此程式碼定義了一個名為 myfunction 的非同步函數。在單獨的檔案中,編寫以下程式碼:

// anotherFile.js
var helper = require('./helper.js');

var start = function (a, b) {
  const result = await helper.myfunction('test', 'test');
};
exports.start = start;

此程式碼從幫助程式檔案存取 myfunction。但是,它嘗試在非非同步啟動函數中呼叫await,這會引發「await 僅在非同步函數中有效」錯誤。

要解決此問題,啟動函數應設為非同步:

async function start(a, b) {
  const result = await helper.myfunction('test', 'test');

  console.log(result);
}

總而言之,使用await 要求封閉函數是非同步函數。當錯誤指定「await 僅在 async 函數中有效」時,請確保呼叫 wait 的函數正確標記為 async。

以上是為什麼 JavaScript 中會出現「await 僅在非同步函數中有效」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn