【问题标题】:Hook into the .then method of a promise挂钩到 promise 的 .then 方法
【发布时间】:2013-06-15 03:16:01
【问题描述】:

(这里是js新手)

我已经超载了RESTAdapter:

/*
  The default RESTAdapter in the application.

  An instance of this object will be created automatically.
*/

MyApp.Adapter = DS.RESTAdapter.extend({
    ajax: function(url, type, hash) {
        var ajax_reply = this._super(url, type, hash);
        console.log('ajax_reply (promise) -> '); console.log(ajax_reply);
        return ajax_reply;
    }
});

现在我得到了promise,我可以在控制台中看到它:

我想挂钩.then 方法,这样我就可以显示ajax 调用返回的json 数据,但不会干扰RESTAdapter 的工作。比如RESTAdapter.find方法是:

  find: function(store, type, id) {
    var root = this.rootForType(type), adapter = this;

    return this.ajax(this.buildURL(root, id), "GET").
      then(function(json){
        adapter.didFindRecord(store, type, json, id);
    }).then(null, DS.rejectionHandler);
  },

我想在控制台中查看通过.then 方法传递的所有 json 回复。我怎样才能“挂钩”到承诺中?

【问题讨论】:

    标签: javascript ember.js promise


    【解决方案1】:

    这样的事情应该可以工作:

    MyApp.Adapter = DS.RESTAdapter.extend({
      ajax: function(url, type, hash) {
        var ajaxPromise = this._super(url, type, hash);
        ajaxPromise.then(function(json){
          console.log(json);
        });
        return ajaxPromise;
      }
    });
    

    【讨论】:

      【解决方案2】:

      要记录所有.ajax() 的回复,请按照@LukeMelia 的建议进行操作。

      要记录对特定MyApp.Adapter.ajax() 呼叫的响应,请尝试:

      MyApp.Adapter.ajax(url, type, hash).then(function(json) {
          console.log(json);
      }, function() {
          console.log('.ajax error');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 1970-01-01
        • 2012-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多