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
Mary-Kate OlsenOriginal
2024-12-14 01:13:09128browse

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 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!

Statement:
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