Promises 有一个then
方法, which you can use to get the eventual return value (fulfillment) or thrown exception (rejection).
promiseMeSomething()
.then(
function (value) {
},
function (reason) {
}
);
If promiseMeSomething
returns a promise that gets fulfilled later
with a return value, the first function (the fulfillment handler) will be called with the value. However, if the promiseMeSomething
function gets rejected later by a thrown exception, the second function (the rejection handler) will be called with the exception.
Note that resolution of a promise is always asynchronous: that is, the fulfillment or rejection handler will always be called in the next turn of the event loop (i.e. process.nextTick
in Node). This gives you a nice guarantee when mentally tracing the flow of your code, namely that then
will always return before either handler is executed.
In this tutorial, we begin with how to consume and work with promises. We'll talk about how to create them, and thus create functions like promiseMeSomething
that return promises,below.