What happens if a promise completes before then is called?

前端 未结 4 651
花落未央
花落未央 2021-01-01 11:51

Let\'s say I have a Promise like this:

var promise = new Promise(function(resolve, reject) {
    // Do some async thing
});
promise.then(functio         


        
4条回答
  •  灰色年华
    2021-01-01 12:25

    A promise has state, which means that even after the promise gets fulfilled, you can attach callbacks using .then to it, and they will be called, with the same result as if the promise was fulfilled after they were attached.

    Fulfilled is the final state of a successful promise. This means that you can attach more handlers to the fulfilled promise in the future, using the promise as a cache for the original response.

    .then() on MDN

    then()

    Calls one of the provided functions as soon as this promise is either fulfilled or rejected. A new promise is returned, whose state evolves depending on this promise and the provided callback functions.

    The appropriate callback is always invoked after this method returns, even if this promise is already fulfilled or rejected. You can also call the then method multiple times on the same promise, and the callbacks will be invoked in the same order as they were registered.

提交回复
热议问题