Home > Web Front-end > JS Tutorial > Why Does async/await Always Return a Promise?

Why Does async/await Always Return a Promise?

DDD
Release: 2024-12-19 16:59:08
Original
549 people have browsed it

Why Does async/await Always Return a Promise?

Why async/await Always Returns Promise

When working with async/await, it's crucial to understand that every async function returns a Promise object. The await keyword operates on Promises, holding your function until the Promise resolves or rejects.

Why Won't console.log() Work Directly?

Unlike synchronous functions, async functions don't immediately return their result. Instead, they return a Promise that, when resolved, contains the result. Thus, console.logging the result of an async function directly will only print the Promise, not its value.

Using then() to Unwrap the Promise

To access the result of an async function, you must either use await or the .then() method. The .then() method accepts a callback that takes the resolved value as an argument. In the example code, the .then() method is used to print the json object.

Why Not Console.log(getJSON())?

In the code snippet you provided, console.log(getJSON()) will return a Promise. This is because await doesn't unwrap the Promise for you. It only makes your function wait for the Promise to resolve. You still need to manually unwrap the Promise using either await or .then().

Conclusion

To utilize async/await effectively, remember that async functions always return Promises. Therefore, to access the result of an async function, you must either use await or call the .then() method on the returned Promise.

The above is the detailed content of Why Does async/await Always Return a Promise?. 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