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

Do Async JavaScript Functions Always Return Promises?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 16:20:12300browse

Do Async JavaScript Functions Always Return Promises?

Async Functions and Implicit Promise Returns

In JavaScript, async functions marked by the async keyword implicitly return promises. This holds true even if you explicitly return non-promise values or don't return anything at all.

Implicit Promise Wrapper

If you don't explicitly return a promise, the value you return will be automatically wrapped in a promise.

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

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

This means that even if the return value is a number, it will be converted into a promise for the purposes of asynchronous processing.

Unwrapped Promises

Promises auto-unwrap, meaning that if you do return a promise for a value from within an async function, you will receive a promise for the value (not a promise for a promise for the value).

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

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

Inconsistent Behavior

The behavior of async functions can indeed seem inconsistent with traditional return statements, as it differs when explicitly returning non-promise values. This is because async functions utilize a special type of function called generators, which don't always return the same value as the return statement.

The above is the detailed content of Do Async JavaScript Functions Always Return Promises?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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