Unlike regular functions, async functions leverage asynchronous processing, allowing them to pause and resume execution. However, this introduces a question: how can one retrieve the returned values?
Initially, a common approach is to try:
async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } console.log(getData());
However, this approach results in a Promise {
The solution lies in wrapping your console.log within an asynchronous Immediately Invoked Function Expression (async IIFE). It looks like this:
async function getData() { return await axios.get('https://jsonplaceholder.typicode.com/posts'); } (async () => { console.log(await getData()) })()
Since Axios returns a promise, you can simplify the getData function by omitting the async/await:
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); }
And then wrap your console.log within the async IIFE as before:
(async () => { console.log(await getData()) })()
By utilizing async-await within async IIFEs, you can effectively retrieve and log the values returned by async functions, unlocking the potential of asynchronous programming.
The above is the detailed content of How do Async Functions Return Values Using Async-Await?. For more information, please follow other related articles on the PHP Chinese website!