Home >Web Front-end >JS Tutorial >Why Does 'await is Only Valid in Async Function' Occur in JavaScript?

Why Does 'await is Only Valid in Async Function' Occur in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 19:16:41545browse

Why Does

"await is Only Valid in Async Function" Error

In JavaScript, the await keyword is only valid within an async function. This error occurs when trying to use await in a non-async function.

Consider the following code snippet:

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

This code defines an asynchronous function called myfunction. In a separate file, the following code is written:

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

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

This code accesses the myfunction from the helper file. However, it attempts to invoke await within the non-asynchronous start function, which raises the "await is only valid in async function" error.

To resolve this issue, the start function should be made asynchronous:

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

  console.log(result);
}

In summary, using await requires the enclosing function to be an async function. When the error specifies "await is only valid in async function," ensure that the function where await is called is correctly marked as async.

The above is the detailed content of Why Does 'await is Only Valid in Async Function' Occur in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn