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; }
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> }
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 });
2. Top-Level Await in Modules:
Modern JavaScript environments support top-level await in modules, allowing you to write:
const time = await latestTime();
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); }); }
This explicit promise syntax highlights several important points:
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!