Home >Web Front-end >JS Tutorial >How to Retrieve Values from Asynchronous Functions Using Async-Await?
Asynchronous Function Value Retrieval Using Async-Await
When working with asynchronous functions in JavaScript that utilize async-await syntax, it is necessary to properly return values for caller functions to utilize.
To return a value from an async function, you must use the return keyword as expected. However, if you attempt to access the return value outside of the async scope, as demonstrated in the provided code sample, you will receive a Promise object in a pending state.
To resolve this issue, it is necessary to wrap your console logging statement in an async IIFE (Immediately Invoked Function Expression), as seen here:
(async () => { console.log(await getData()); })();
This allows the async scope to be preserved, enabling the function to access and return the desired value.
Note that since the axios library returns a promise, it is also possible to omit the async-await syntax for the getData function, as shown below:
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); }
You can then wrap the console logging statement in an async IIFE as described above to retrieve the value from the getData function. More information on async/await can be found online.
The above is the detailed content of How to Retrieve Values from Asynchronous Functions Using Async-Await?. For more information, please follow other related articles on the PHP Chinese website!