Error: "await is only valid in async function"
The provided JavaScript code encountered an error when attempting to use the "await" keyword within a non-async function. This error specifically points to the use of "await" within the "start" function.
Explanation:
The "await" keyword can only be used inside the body of an asynchronous function, which is denoted by the "async" keyword. In the provided code, the "myfunction" is defined as an asynchronous function, allowing the use of "await" within its body. However, the "start" function is defined as a regular function that does not have the "async" keyword.
Solution:
To resolve this issue, the "start" function needs to be converted into an asynchronous function. This can be achieved by adding the "async" keyword before the function definition, as shown below:
async function start(a, b) { .... const result = await helper.myfunction('test', 'test'); }
Now, the "start" function can use "await" to wait for the completion of the "myfunction" call and proceed with its execution.
The above is the detailed content of Why Does 'await' Fail Outside an Async Function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!