P粉6161110382023-08-22 12:43:32
When a promise is resolved/rejected, it calls its success/error handler:
var promiseB = promiseA.then(function(result) { // 用result做一些事情 });The
then
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:
promiseB = promiseA.then(function(result) { return result + 1; });
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.
P粉1551282112023-08-22 00:10:42
The
then function of
promiseA
returns a new promise (promiseB
) that resolves immediately after promiseA
resolves, with a value of The value returned in the success function of promiseA
.
In this case, promiseA
resolves to a value - result
, which then immediately resolves promiseB
with the value of result 1
.
Accessing the value of promiseB
is the same as accessing the result of promiseA
.
promiseB.then(function(result) { // 这里你可以使用promiseB的结果 });
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:
let result = await functionThatReturnsPromiseA(); result = result + 1;
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 an async
function. So zooming in a little bit, the above code needs to be contained within a function:
async function doSomething() { let result = await functionThatReturnsPromiseA(); return result + 1; }
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 use result = 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.