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; }
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> }
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 });
Top-Level await
Modern environments support top-level await in modules, allowing you to write code like this:
const time = await latestTime();
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); }); }
In this representation:
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!