Home > Web Front-end > JS Tutorial > Why Do Async Functions Always Return Promises in JavaScript?

Why Do Async Functions Always Return Promises in JavaScript?

Mary-Kate Olsen
Release: 2024-12-14 01:13:09
Original
127 people have browsed it

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
});
Copy after login

In modern environments, top-level await is supported within modules:

const time = await latestTime();
Copy after login

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);
  });
}
Copy after login

In this callback version:

  • The promise executor function (passed to new Promise) runs synchronously, starting the web3.eth.getBlock operation.
  • Any errors within the promise executor or callbacks are caught and converted to promise rejections.

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!

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