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

Do Async Functions Always Return Promises?

Mary-Kate Olsen
Release: 2024-12-25 02:09:12
Original
812 people have browsed it

Do Async Functions Always Return Promises?

Question: Do Async Functions Implicitly Return Promises?

In JavaScript, async functions are declared using the async keyword and are frequently thought to automatically return promises. However, this raises a potential inconsistency: when a non-promise value is explicitly returned, the function appears to wrap the value in a promise.

Answer: All Async Functions Return Promises

The behavior observed is correct: all async functions implicitly return promises. Specifically:

  • When an async function returns without an explicit return statement, it returns a promise resolved to undefined.
  • When an async function explicitly returns a non-promise value, it wraps the value in a promise resolved to that value.
  • Even when an async function contains an await expression, the returned value is still a promise, wrapping the result of the await expression.
  • If an error is thrown inside an async function, the returned promise is rejected with that error.

Example:

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

// Logs 4, as the returned promise resolves to 4.
increment(3).then(num => console.log(num));
Copy after login

Wrapping Behavior:

This wrapping behavior is unique to generator functions. For instance, generator functions also return promises, but in a different manner:

function* foo() {
  return 'test';
}

// Logs an object, not "test".
console.log(foo());

// Logs 'test' by explicitly calling .next() on the generator function.
console.log(foo().next().value);
Copy after login

The above is the detailed content of Do Async Functions 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