What happens if a promise completes before then is called?

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

    The then callback will never get called before the promise is resolved, which is what I think you mean by complete. However, if a promise is resolved before it is returned from a function, any additional success callbacks chained after that moment will still be executed. For example,

    function getMeAResolvedPromise() {
        var prom = new Promise();
        prom.resolve('some val');
        return prom;
    }
    
    ...
    
    getMeAResolvedPromise.then(function(result) {
        // this will still be executed
    });
    

提交回复
热议问题