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; };
When invoking getJSON(), it returns a Promise because the await statement merely suspends execution until the request completes:
console.log(getJSON()); // returns Promise
In contrast, when chaining .then(), the result of the Promise is finally exposed:
getJSON().then(json => console.log(json)); // prints { foo: 'bar' }
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!