Home > Article > Web Front-end > 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:
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>
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>
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>
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>
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!