How to get the value of promise?
P粉116631591
2023-08-21 13:47:33
<p>I was looking at the Angular documentation for examples of <code>$q</code>, but I thought this might work for promises in general. The example below is copied directly from their documentation, including their comments: </p>
<pre class="brush:php;toolbar:false;">promiseB = promiseA.then(function(result) {
return result 1;
});
// When promiseA is resolved, promiseB will be resolved immediately, and its value will be the result of promiseA plus 1</pre>
<p>I'm not sure how this works. If I could call <code>.then()</code> on the result of the first <code>.then()</code>, chaining them together, I know I could do that , then <code>promiseB</code> is a promise object of type <code>Object</code>. It is not a <code>Number</code>. So what do they mean by "its value will be the result of promiseA plus 1"? </p>
<p>Should I access it like <code>promiseB.value</code>? How can a success callback return a promise and return "result 1"? I'm missing something. </p>
When a promise is resolved/rejected, it calls its success/error handler:
Thethen
method also returns a promise: promiseB which will be resolved/rejected based on the return value of promiseA's success/error handler.The success/error handler of promiseA can return three possible values that will affect the outcome of promiseB:
With this understanding, you can understand the following:
The then call returns promiseB immediately.
When promiseA is resolved, it passes the result to promiseA's success handler.
Since the return value is promiseA's result 1 and the success handler returns a value (option 2 above), promiseB will be resolved immediately and promiseB's success handler will be passed promiseA's result 1.
The
then
function of
promiseA
returns a new promise (promiseB
) that resolves immediately afterpromiseA
resolves, with a value of The value returned in the success function ofpromiseA
.In this case,
promiseA
resolves to a value -result
, which then immediately resolvespromiseB
with the value ofresult 1
.Accessing the value of
promiseB
is the same as accessing the result ofpromiseA
.Starting with ECMAScript 2016 (ES7, 2016),
async
/await
becomes standard in JavaScript, which allows an alternative syntax to the above approach. Now you can write like this:There is no promiseB now, because we used
await
to unwrap the result of promiseA, and you can use it directly.However,
await
can only be used inside anasync
function. So zooming in a little bit, the above code needs to be contained within a function:It should be clear that the return value of the
doSomething
function in this example is still a promise, because the async function returns a promise. So if you want to access the return value, you need to useresult = await doSomething()
, which can only be used inside another async function. Basically, in the parent async context, you have direct access to the values produced by the child async context.