Home > Web Front-end > JS Tutorial > Does async/await in JavaScript Always Return a Promise, and Why?

Does async/await in JavaScript Always Return a Promise, and Why?

Barbara Streisand
Release: 2024-12-12 11:54:10
Original
800 people have browsed it

Does async/await in JavaScript Always Return a Promise, and Why?

async/await: Promise Unveiled

Promises are a fundamental aspect of asynchronous programming in JavaScript. When it comes to async/await, it's important to demystify the notion that async functions always return a Promise.

The await keyword, placed before a Promise-returning function call, suspends the execution of the current function until the Promise is either resolved or rejected. However, this suspension does not unwrap the Promise. The result of the Promise is still encapsulated within the returned Promise object.

To illustrate, consider the following code that simulates an asynchronous request:

const getJSON = async () => {
  const request = () => new Promise((resolve, reject) => (
    setTimeout(() => resolve({ foo: 'bar' }), 2000)
  ));

  const json = await request();
  return json;
};
Copy after login

When invoking getJSON(), it returns a Promise because the await statement merely suspends execution until the request completes:

console.log(getJSON()); // returns Promise
Copy after login

In contrast, when chaining .then(), the result of the Promise is finally exposed:

getJSON().then(json => console.log(json)); // prints { foo: 'bar' }
Copy after login

Why can't you bypass the Promise wrapping with console.log(getJSON())? This is a fundamental property of Promises. Promises represent asynchronous operations, and their outcomes are not known until they resolve or reject. External access to the result is intentionally prohibited, ensuring that the Promise remains the sole mediator of the result.

Remember, async/await makes working with Promises more convenient by suspending execution when Promises are encountered, but it does not remove the necessity of unwrapping Promises to access their results.

The above is the detailed content of Does async/await in JavaScript Always Return a Promise, and Why?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template