Home >Web Front-end >JS Tutorial >How Do Async Functions and Promises Work Together in JavaScript?

How Do Async Functions and Promises Work Together in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 20:15:17926browse

How Do Async Functions and Promises Work Together in JavaScript?

Async Functions and Promises

When working with asynchronous operations, it's crucial to understand how async functions and promises interact.

Async Functions Always Return Promises

Unlike regular functions, async functions always return a promise, indicating the completion of their asynchronous operations. This makes handling asynchronous operations in sequential code more straightforward.

Example:

async function latestTime() {
  const bl = await web3.eth.getBlock('latest');
  return bl.timestamp;
}

Returning Primitive Values vs. Promises

Although the function returns a primitive value (bl.timestamp), the latestTime() function itself returns a promise. This can lead to confusion when attempting to access the return value.

Using Promises

To access the resolved value of the returned promise, you need to use the then() method:

latestTime().then((time) => {
  console.log(time);
});

Alternatively, in modern JavaScript environments, you can use top-level await:

const time = await latestTime();
console.log(time);

Explicit Promise Handling

For clarity, here's a more explicit representation of how the async function behaves in terms of promise callbacks:

function latestTime() {
    return new Promise((resolve, reject) => {
        web3.eth.getBlock('latest').then((bl) => {
            resolve(bl.timestamp);
        })
    });
}

The above is the detailed content of How Do Async Functions and Promises Work Together 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