javascript - 当 api 调用超时时,BackboneJS 无法转到 .fail

标签 javascript jquery backbone.js jquery-deferred

我是 Backbone 新手。我找到了添加 Deferred 的代码,以便我们可以添加 Promise。这是代码

getPatientInfo: function fetch(options) {
   var deferred = $.Deferred();
   Backbone.Model.prototype.fetch.call(this, _.extend({ 
     deferred: deferred
     }, 
     options));
   return deferred;
 },

调用getItem函数的代码是这样的

  this.item.getPatientInfo().done(_.bind(function() {
    this.renderPatient(this.item);
  },this))
  .fail(function(error){
    // This won't show unlike native $.ajax .fail where it will show the error
    // Not sure why it's not working
    console.log(error);
  });

但是,当我尝试模拟关闭网络等故障时,.fail 将无法捕获失败的 GET 请求。我不会执行 console.log(error);

但是,如果我使用 native jquery 更改它,例如使用 $.ajax().success().error(function(error){console.log(error)}),则 .error 将起作用,我将能够在我的控制台选项卡中查看错误。

出了什么问题?

更新是为了防止出现问题,但我认为并不理想。因为它丢失而修补它并不是一个好主意

  this.item.getPatientInfo().done(_.bind(function() {
    if (this.item.attributes.info !== undefined) {
      this.renderPatient(this.item);
    }
  },this))

最佳答案

Backbone 模型已经返回了延迟,我认为这种过于复杂的实现没有充分的理由 - 使用 Backbone 比反对它更好。例如

var SomeModel = Backbone.Model.extend({
    url: 'http://jsonplaceholder.typicode.com/posts/1'
});

var someModel = new SomeModel();
someModel.fetch()
.done(function(response) {
    console.log('Post title: ', response.title);
    console.log('Post body: ', response.body);
})
.fail(function(jqXHR, textStatus, errorThrown) {
    console.log('failed');
});

fiddle :http://jsfiddle.net/ferahl/5zzzchpq/

请注意,您还可以访问 done 中的新属性,即 someModel.get('title'),或者您可以使用 模型在成功和失败时触发的 'sync''error' 事件。

关于javascript - 当 api 调用超时时,BackboneJS 无法转到 .fail,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32385077/

相关文章:

javascript - 获取 Backbone 集合时出错: A "url" property or function must be specified

javascript - 如何使用 nvd3 触发调整大小事件?

javascript - 需要有关 javascript 和 Visual C++ 通信的帮助,反之亦然

javascript - Mongoose - 获取嵌套数组/动态生成的 $and 子句中 id 的所有元素

jquery - 如何在按钮点击后弹出确认对话框

javascript - 当浏览器调整大小时,不断移动视频上可调整大小/可拖动的图像

javascript - 运行一个 node.js 程序,该程序对本地计算机上运行的 Express 服务器进行 fetch 调用

javascript - 带有 JSViews 事件绑定(bind)的 JSRender 与全局辅助函数抛出错误 e.apply 不是函数

backbone.js - 如何使用启用 requirejs 的 yeoman 引导 Backbone 应用程序

javascript - underscore.js 中 if 语句的字符串连接