Home > Web Front-end > JS Tutorial > Why Do Async JavaScript Functions Always Return Promises, Even When Returning Primitive Values?

Why Do Async JavaScript Functions Always Return Promises, Even When Returning Primitive Values?

Mary-Kate Olsen
Release: 2024-12-18 15:05:13
Original
580 people have browsed it

Why Do Async JavaScript Functions Always Return Promises, Even When Returning Primitive Values?

Async Function Returning Promise: A Detailed Explanation

In JavaScript, understanding the interaction between async functions and promises is crucial. Async functions, introduced by JavaScript ES2017, allow for asynchronous operations without the need for callbacks. They return a promise, which represents the eventual result of the asynchronous operation.

Consider the following async function:

async function latestTime() {
  const bl = await web3.eth.getBlock('latest');
  console.log(bl.timestamp); // Returns a primitive
  console.log(typeof bl.timestamp.then == 'function'); // Returns false - not a promise
  return bl.timestamp;
}
Copy after login

The confusion arises when the function latestTime is not used in another async function and is assigned to a variable outside the async context:

const time = latestTime(); // Promise { <pending> }
Copy after login

As a result, the time variable becomes a pending promise instead of the primitive value returned by the async function. This happens because async functions always return a promise, even if they return a primitive value within their body.

To handle this situation properly, you have two options:

1. Use Promises Directly:

In non-async contexts, such as event handlers or module top levels, promises must be handled directly. You can use the then() method:

latestTime()
  .then(time => {
    console.log(time);
  })
  .catch(error => {
    // Handle/report error
  });
Copy after login

2. Top-Level Await in Modules:

Modern JavaScript environments support top-level await in modules, allowing you to write:

const time = await latestTime();
Copy after login

Under the Hood:

To understand how the JavaScript engine handles an async function, consider its rewrite as an explicit promise callback:

function latestTime() {
  return new Promise((resolve, reject) => {
    web3.eth.getBlock('latest')
      .then(bl => {
        console.log(bl.timestamp);
        console.log(typeof bl.timestamp.then == 'function');
        resolve(bl.timestamp);
      })
      .catch(reject);
  });
}
Copy after login

This explicit promise syntax highlights several important points:

  • The promise executor function (passed to new Promise) runs synchronously, which is why web3.eth.getBlock is called immediately.
  • Errors thrown within the promise executor or its callbacks are caught and propagate as promise rejections.

The above is the detailed content of Why Do Async JavaScript Functions Always Return Promises, Even When Returning Primitive Values?. 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