Home > Web Front-end > JS Tutorial > Do Async Functions in JavaScript Always Return Promises?

Do Async Functions in JavaScript Always Return Promises?

Susan Sarandon
Release: 2024-12-22 09:54:37
Original
728 people have browsed it

Do Async Functions in JavaScript Always Return Promises?

Implicit Promises in Async Functions

In JavaScript, async functions are functions that can asynchronously await a promise to complete and return its value. However, a common misconception is that async functions implicitly return a promise for the value they return.

Understanding the Return Value

While it may appear that async functions implicitly return a promise, this is not entirely accurate. The return value of an async function can be one of two things:

  • A non-promise value: When an async function explicitly returns a non-promise value, it automatically wraps that value in a promise.
  • A promise: The return value of an async function that is itself a promise remains unchanged.

Example with Non-Promise Value:

async function increment(num) {
  return num + 1;
}

increment(3).then(num => console.log(num)); // Logs: 4
Copy after login

Here, we return a number from the async function. However, the output is retrieved through .then(), indicating that it is a promise that has been resolved to the value 4.

Explicit Promises:

If we explicitly return a promise from an async function, we receive a promise for that value, not a promise for a promise.

async function increment(num) {
  return Promise.resolve(num + 1);
}

increment(3).then(num => console.log(num)); // Logs: 4
Copy after login

Exceptional Cases:

  • Empty Async Functions: Even if an async function has no explicit return statement, it still returns a promise for undefined.
  • Await in Async Functions: Using await within an async function does not affect the type of the return value. It will still be wrapped in a promise if the returned value is not a promise.

Conclusion

Async functions in JavaScript implicitly wrap non-promise return values in a promise. However, if the return value is already a promise, it is left untouched. This behavior differs from traditional return statements but is consistent with the underlying principles of generators in ES6.

The above is the detailed content of Do Async Functions in JavaScript Always Return Promises?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template