Home >Web Front-end >JS Tutorial >How to Access Return Values from Async Functions with async-await?
Returning Values from Async Functions with async-await
When calling an asynchronous function using the async-await syntax, accessing the return value directly can result in a pending Promise. This article explores how to resolve this issue.
Awaiting Values Outside of Async Scope
Your initial attempt to log the return value of the getData function was unsuccessful because you were attempting to await a value outside of an asynchronous scope. The async-await syntax can only be used within asynchronous functions or blocks (denoted by the async keyword).
Asynchronous IIFE to Wrap Logging
To resolve this issue, you can wrap your console.log statement in an asynchronous Immediately Invoked Function Expression (IIFE) like this:
(async () => { console.log(await getData()); })();
This ensures that the logging is performed within an asynchronous context, allowing the await syntax to work correctly.
Omitting Async/Await for Promise Returns
In your example, axios returns a Promise. In such cases, you can simplify your code by omitting the async/await syntax for your getData function and using the Promise object directly:
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); }
Then, you can still use the asynchronous IIFE to log the result as before:
(async () => { console.log(await getData()); })();
By following these approaches, you can ensure that values returned from asynchronous functions using async-await are correctly accessed and handled.
The above is the detailed content of How to Access Return Values from Async Functions with async-await?. For more information, please follow other related articles on the PHP Chinese website!