What happens if a promise completes before then is called?

前端 未结 4 654
花落未央
花落未央 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:24

    As others have already pointed out, you can add callbacks with .then before or after the promise has been resolved, and you can even add more than one callback.

    These callbacks will be called in the order they were added, but always asynchronously, after the current turn of the event loop. So if the promise has already been resolved when you add a .then, your handler will be called immediately, but in the "ascynchronous sense".

    The Promises/A+ spec says:

    [...] onFulfilled and onRejected execute asynchronously, after the event loop turn in which then is called, and with a fresh stack.

提交回复
热议问题