Home > Web Front-end > JS Tutorial > body text

How to Access Return Values from Async Functions with async-await?

DDD
Release: 2024-11-12 22:39:02
Original
308 people have browsed it

How to Access Return Values from Async Functions with async-await?

Returning Values from Async Functions with async-await

When calling an asynchronous function using the async-await syntax, accessing the return value directly can result in a pending Promise. This article explores how to resolve this issue.

Awaiting Values Outside of Async Scope

Your initial attempt to log the return value of the getData function was unsuccessful because you were attempting to await a value outside of an asynchronous scope. The async-await syntax can only be used within asynchronous functions or blocks (denoted by the async keyword).

Asynchronous IIFE to Wrap Logging

To resolve this issue, you can wrap your console.log statement in an asynchronous Immediately Invoked Function Expression (IIFE) like this:

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

This ensures that the logging is performed within an asynchronous context, allowing the await syntax to work correctly.

Omitting Async/Await for Promise Returns

In your example, axios returns a Promise. In such cases, you can simplify your code by omitting the async/await syntax for your getData function and using the Promise object directly:

function getData() {
  return axios.get('https://jsonplaceholder.typicode.com/posts');
}
Copy after login

Then, you can still use the asynchronous IIFE to log the result as before:

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

By following these approaches, you can ensure that values returned from asynchronous functions using async-await are correctly accessed and handled.

The above is the detailed content of How to Access Return Values from Async Functions with 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template