Home > Web Front-end > JS Tutorial > Async Functions in JavaScript: Implicit Promise or Explicit Return Value?

Async Functions in JavaScript: Implicit Promise or Explicit Return Value?

Susan Sarandon
Release: 2024-12-17 18:36:12
Original
702 people have browsed it

Async Functions in JavaScript: Implicit Promise or Explicit Return Value?

Async Functions: Implicit Promise Return or Explicit Control?

Async functions in JavaScript, denoted by the async keyword, are often said to implicitly return promises. However, a closer examination reveals that the reality is more nuanced.

By default, an async function will indeed return a promise if a promise is not explicitly returned. This means that the following code:

async function getVal() {
  const result = await doSomethingAsync();
  return result;
}
Copy after login

is equivalent to:

async function getVal() {
  const result = await doSomethingAsync();
  return Promise.resolve(result);
}
Copy after login

However, if you explicitly return a non-promise value, the function will automatically wrap it in a promise. For instance, in the following example:

async function getVal() {
  return doSomethingNonAsync();
}
Copy after login

getVal will actually return a Promise object containing the result of doSomethingNonAsync().

It's worth noting that this behavior differs from traditional JavaScript functions. When you explicitly return a primitive value from a regular function, it's immediately returned. Async functions, however, always return a promise, wrapping non-promise values as needed.

This may seem inconsistent, but it meshes with the concept of generators in ES6. Generators are functions that don't return the same value as their return statement. Instead, they yield a series of values, which can be iterated over using the yield operator.

For example:

function* getVal() {
  yield doSomethingAsync();
  return 'finished';
}

// Logs an object.
console.log(getVal());

// Logs 'yikes' and then 'finished'.
for (const val of getVal()) {
  console.log(val);
}
Copy after login

The above is the detailed content of Async Functions in JavaScript: Implicit Promise or Explicit Return Value?. 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