Home > Web Front-end > JS Tutorial > How do Async Functions Return Values Using Async-Await?

How do Async Functions Return Values Using Async-Await?

Barbara Streisand
Release: 2024-11-11 13:43:02
Original
894 people have browsed it

How do Async Functions Return Values Using Async-Await?

How Async Functions Return Values Using Async-Await

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?

The Original Query

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());
Copy after login

However, this approach results in a Promise { } output, as async functions require special handling.

The Magic of Async-Await in Async IIFE

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())
})()
Copy after login

Async-Await with Promises

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');
}
Copy after login

And then wrap your console.log within the async IIFE as before:

(async () => {
   console.log(await getData())
})()
Copy after login

Conclusion

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template