Home >Web Front-end >JS Tutorial >How to Await and Return Values from Async Functions in JavaScript?
How to Await and Return Values from Async Functions
When working with async functions, returning values can be different from synchronous functions. In this article, we'll explore how to handle this behavior using async-await.
Problem:
Suppose you have an async function getData that fetches data from an API using Axios. To retrieve the data and log it, you try the following code:
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } console.log(getData());
However, instead of logging the data, you get a Promise with a pending state.
Solution:
The issue here is that you're attempting to await the result of an async function outside of an async scope. To fix this, you need to encapsulate the console.log within an async IIFE (Immediately Invoked Function Expression):
async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } (async () => { const result = await getData(); console.log(result); })();
This pattern allows you to await the result of the getData function within an async scope.
Alternative Syntax:
If your async function doesn't rely on returning a promise (e.g., Axios returns a promise), you can simplify the syntax by removing the async and await keywords from getData.
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); }
Then, use the same IIFE structure as before to await the result:
(async () => { console.log(await getData()); })();
More Information:
For more details on async/await and asynchronous programming in JavaScript, refer to the following resources:
The above is the detailed content of How to Await and Return Values from Async Functions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!