Home >Web Front-end >JS Tutorial >Why Does 'await is only valid in async function' Appear When Using `await` Outside an Async Function?
When attempting to utilize the await keyword in JavaScript, you may encounter the error "await is only valid in async function." This error arises when the await keyword is utilized incorrectly.
In your scenario, the error pertains to the start function rather than the myfunction function. The myfunction function is correctly defined as an asynchronous function, allowing you to utilize the await keyword within it. However, the start function is not defined as an asynchronous function.
To rectify this, the start function should be modified to become an asynchronous function, enabling the use of the await keyword within it. Here is an example of how the start function could be rewritten:
async function start(a, b) { const result = await myfunction(a, b); console.log(result); // Do something with the result }
By making the start function asynchronous, you can now utilize the await keyword to pause the execution of the function until the myfunction function has completed its execution. This is crucial as it guarantees that the result variable contains the expected data before proceeding with subsequent code.
The above is the detailed content of Why Does 'await is only valid in async function' Appear When Using `await` Outside an Async Function?. For more information, please follow other related articles on the PHP Chinese website!