"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does async/await Always Return a Promise?

Why Does async/await Always Return a Promise?

Posted on 2025-03-23
Browse:190

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3