Why Does async/await Always Return a Promise?
Using async/await functionality can be puzzling at first, especially when it comes to handling the promise returned by the async function. Let's delve into the behavior highlighted in the provided code:
<br>const getJSON = async () => {<br> const request = () => new Promise((resolve, reject) => (</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">setTimeout(() => resolve({ foo: 'bar'}), 2000)
));
const json = await request();
return json;
}
When executing getJSON(), the function returns a Promise object. This happens because every async function returns a Promise under the hood. The await keyword operates on this Promise, suspending the function execution until the Promise resolves or rejects.
In the example, await waits for request() to resolve. However, it doesn't automatically unwrap the Promise. You need to explicitly handle the returned Promise either using await or .then().
Using .then(), as seen in the provided code:
<br>getJSON().then(json => console.log(json)); // prints { foo: 'bar' }<br>
invokes the callback function when the Promise resolves and passes the result as the json parameter. This approach allows access to the resolved value within the callback.
On the other hand, directly logging the result of the async function using console.log(getJSON()) returns a Promise object because it doesn't unwrap the Promise. The Promise model ensures that you can only access the result of a Promise from within the Promise itself or by using an explicit unwrapping method like .then().
The above is the detailed content of Why Do Async/Await Functions Always Return a Promise?. For more information, please follow other related articles on the PHP Chinese website!