Home >Web Front-end >JS Tutorial >What\'s the Difference Between `return await Promise` and `return Promise` in Asynchronous JavaScript?

What\'s the Difference Between `return await Promise` and `return Promise` in Asynchronous JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 06:20:15562browse

What's the Difference Between `return await Promise` and `return Promise` in Asynchronous JavaScript?

Understanding the Distinction between return await promise and return promise

In asynchronous JavaScript, the behavior of return await promise and return promise has often been a subject of debate. While both expressions involve returning promises, subtle differences can arise in specific scenarios.

Asynchronous Functions

In the provided code samples, two asynchronous functions (delay1Second) are defined. The first function uses return await to wrap the result of the delay promise in another promise, while the second simply returns the delay promise without awaiting it.

Observable Behavior

In most cases, there is no discernible difference between these two constructs. Both delay1Second functions return promises that resolve after 1 second. However, as mentioned in the question, the return await version may consume slightly more memory due to the creation of an intermediate promise object.

Exception Handling

However, a critical distinction emerges when these expressions are used within try-catch blocks. Consider the following example:

async function rejectionWithReturnAwait() {
  try {
    return await Promise.reject(new Error());
  } catch (e) {
    return 'Saved!';
  }
}

async function rejectionWithReturn() {
  try {
    return Promise.reject(new Error());
  } catch (e) {
    return 'Saved!';
  }
}

In the first function (rejectionWithReturnAwait), the return is wrapped in await. This means that the function will wait for the rejected promise to reject, which will cause an exception to be thrown within the async block. As a result, the catch handler is reached, and the function returns a promise resolving to 'Saved!'.

Conversely, in the second function (rejectionWithReturn), the promise is directly returned without being awaited within the async function. This means that the exception does not occur within the async block, and the catch handler is not executed. Instead, the caller simply receives the rejected promise.

The above is the detailed content of What\'s the Difference Between `return await Promise` and `return Promise` in Asynchronous 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