Home > Web Front-end > JS Tutorial > body text

What Are the Return Values of Async Functions and How Do They Relate to Promises?

DDD
Release: 2024-10-18 10:35:29
Original
507 people have browsed it

What Are the Return Values of Async Functions and How Do They Relate to Promises?

Async Functions: Understanding Return Values and Promises

While async functions allow you to write code in a synchronous style, they inherently return promises. This may lead to confusion regarding the return value of your code.

Promises: A Quick Overview

Promises are objects that represent the eventual completion or failure of an asynchronous operation. They provide two key methods:

  • then(resolve, reject): Processes the result of the operation when it's successful (resolve) or detects an error (reject).
  • catch(reject): Handles errors asynchronously.

Async Functions and Promises

Async functions always return a promise, even if you don't explicitly use the await keyword. This promise represents the result of the async operation. If the function throws an error, the promise will reject with that error.

Usage:

Promises with Callback Functions:

<code class="javascript">const myAsyncFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Asynchronous value');
    }, 1000);
  });
};

myAsyncFunction()
  .then(result => {
    console.log(`Callback Result: ${result}`);
  })
  .catch(error => {
    console.log(`Error: ${error}`);
  });</code>
Copy after login

Promises with Async/Await:

<code class="javascript">async function myAsyncFunction() {
  const result = await new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('Asynchronous value');
    }, 1000);
  });
  return result;
}

myAsyncFunction()
  .then(result => {
    console.log(`Await Result: ${result}`);
  })
  .catch(error => {
    console.log(`Error: ${error}`);
  });</code>
Copy after login

In these examples, the myAsyncFunction returns a promise that resolves with the value 'Asynchronous value' after a 1-second delay. The then and catch methods handle the resolved or rejected state, respectively.

Returning the Promise

If you want to return the promise itself without any modification, you can simply write:

<code class="javascript">const myAsyncFunction = () => {
  return new Promise(...);
};</code>
Copy after login

Returning a Modified Value

To return a modified value from an async function, you need to handle the Promise result within the then method and return the modified value. For example:

<code class="javascript">async function myAsyncFunction() {
  const result = await new Promise(...);
  return result.toUpperCase();
}</code>
Copy after login

This function returns a promise that resolves with the uppercase version of the result.

The above is the detailed content of What Are the Return Values of Async Functions and How Do They Relate to Promises?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!