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

How Do Async Functions in JavaScript Always Return a Promise?

Patricia Arquette
Release: 2024-12-20 11:50:09
Original
379 people have browsed it

How Do Async Functions in JavaScript Always Return a Promise?

Understanding the Relationship between Async Functions and Promises

In JavaScript, async functions simplify asynchronous programming by allowing you to write code that appears synchronous while it executes asynchronously. However, understanding how async functions interact with promises can be crucial.

The Problem

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

When you call latestTime(), you might expect to receive the primitive value of the timestamp from web3.eth.getBlock. However, instead, you get a pending promise, as indicated by the following:

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

Why a Promise is Returned

Async functions always return a promise. This promise is settled when the function completes its asynchronous operation and provides the final value or rejects with an error. In the case of latestTime(), the promise is settled with the timestamp primitive.

How to Handle the Promise

Outside of another async function, you can use the then method on the promise to access the resolved value or handle any errors:

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

Top-Level await

Modern environments support top-level await in modules, allowing you to write code like this:

const time = await latestTime();
Copy after login

This syntax simplifies working with promises at the module level. However, remember that unhandled promise rejections in modules can cause the module to fail to load.

Understanding Async Functions with Promises

To better understand how async functions work in conjunction with promises, it's helpful to consider how the JavaScript engine compiles your async function into a promise executor function:

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

In this representation:

  • The async function is represented as a promise executor function passed to new Promise.
  • The asynchronous operation starts when web3.eth.getBlock is called synchronously.
  • Promise callbacks are used to resolve or reject the promise.

As a result, the async function effectively returns a promise to the calling code.

The above is the detailed content of How Do Async Functions in JavaScript Always Return a Promise?. 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