weixin_33697898 2015-12-21 16:57 采纳率: 0%
浏览 12

Ecma 6 Promise完成

I am experimenting with Promise from ES6, but I can't find any alternative to complete as in jQuery ajax. I need to execute function after all the registered handlers with "then".

Thanks!

  • 写回答

1条回答 默认 最新

  • weixin_33712881 2015-12-22 00:51
    关注

    As mentioned by Bergi, what you want is the disposer pattern. Your central conception of a promise appears to be a bit off, and I think that is making this harder for you to reason about. When you call .then, you are not conceptually "attaching a handler", you are creating a new promise that will by definition resolve after all of its .then handlers have run.

    Given your central issue based on code like this:

    // a.js
    module.exports = function(){
        // Where 'Promise.resolve()' is a stand in for your ajax.
        return Promise.resolve()
            .then(function(){
                // Want this to run after 'B'.
            });
    }
    
    // b.js
    var makePromise = require('./a');
    module.exports = function specialMakePromise(){
        return makePromise().then(function(){
            // Should run first.
        });
    }
    

    They will always run in the wrong order, because by definition, the .then handler from a.js must run and complete before the .then handler from b.js.

    One way to approach this problem would instead to structure your code like this:

    // a.js
    module.exports = function(callback){
        return Promise.resolve()
            .then(callback)
            .then(function(){
                // Want this to run after 'B'.
            });
    }
    
    // b.js
    var makePromise = require('./a');
    module.exports = function specialMakePromise(){
        return makePromise(function(){
            // Should run first.
        });
    }
    
    评论

报告相同问题?