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.
        });
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度