Home >Web Front-end >JS Tutorial >How to Retrieve Values from Async Functions with Async-Await in JavaScript?
How to Retrieve Values from Async Functions with Async-Await
In JavaScript, understanding how to return values from async functions is crucial. Let's delve into a scenario:
Scenario:
Consider the following code snippet:
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } console.log(getData());
Problem:
If you execute this code, you'll encounter a "Promise {
Solution:
To address this issue, we must adhere to the rule that asynchronous operations should only be awaited within another asynchronous context. In our case, we can achieve this by encapsulating the console.log() statement within an async IIFE (immediately invoked function expression):
async function getData() { return await axios.get('https://jsonplaceholder.typicode.com/posts'); } (async () => { console.log(await getData()) })()
This ensures that the console.log() statement is only executed once the GetData() function has completed its asynchronous operation and returned the data.
Alternatively:
If axios returns a Promise, as it does in your code, we can simplify the code by removing the async and await from getData(). The code then becomes:
function getData() { return axios.get('https://jsonplaceholder.typicode.com/posts'); } (async () => { console.log(await getData()) })()
This still achieves the same result by awaiting the getData() function within an asynchronous context.
The above is the detailed content of How to Retrieve Values from Async Functions with Async-Await in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!