Home >Web Front-end >JS Tutorial >Why Do Async Functions Always Return Promises in JavaScript?
Async Function Returning Promise Instead of Value
In async/await programming, an async function always returns a promise. This promise represents the eventual completion of the function's asynchronous work.
When calling an async function in another async context, you can utilize await to pause until the promise settles. However, in a non-async context (often the top level or event handler), you must directly use the promise:
latestTime() .then(time => { console.log(time); }) .catch(error => { // Handle/report error });
In modern environments, top-level await is supported within modules:
const time = await latestTime();
To better understand, let's examine an explicit promise callback version of your async 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 callback version:
The above is the detailed content of Why Do Async Functions Always Return Promises in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!