Home  >  Article  >  Web Front-end  >  How to Retrieve Values from Async Functions with Async-Await in JavaScript?

How to Retrieve Values from Async Functions with Async-Await in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 04:17:02676browse

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 { }" message in the console. Instead of returning the expected data, we receive this pending promise. The reason for this is that we're attempting to access the result of an asynchronous function outside of an asynchronous context.

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!

Statement:
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