【问题标题】:How to return a new promise instead of an error on a failed ajax request in Javascript/Jquery?如何在Javascript / Jquery中失败的ajax请求返回新的承诺而不是错误?
【发布时间】:2013-10-15 17:19:44
【问题描述】:

我有一个创建deferred 对象的函数。在fail 上,我正在调用一个回退函数,该函数反过来创建并返回它自己的deferred/promise 对象。我想返回这个 fallback-deferred 的结果,但我只能在初次调用时返回 error

这是我正在做的事情:

 // method call
 init.fetchConfigurationFile(
      storage,
      "gadgets",
      gadget.getAttribute("data-gadget-id"),
      pointer
  ).then(function(fragment) {
      console.log("gotcha");
      console.log(fragment);
  }).fail(function(error_should_be_fragment) {
      console.log("gotcha not");
      console.log(error_should_be_fragment);
  });

我的fetchConfiguration 调用尝试从本地存储加载,如果我需要的文档/附件不在本地存储中,则回退到从文件加载。

  init.fetchConfigurationFile = function (storage, file, attachment, run) {
    return storage.getAttachment({"_id": file, "_attachment": attachment})
      .then(function (response) {
        return jIO.util.readBlobAsText(response.data);
      })
      .then(function (answer) {
        return run(JSON.parse(answer.target.result))
      })
      .fail(function (error) {
        // PROBLEM
        console.log(error);
        if (error.status === 404 && error.id === file) {
          return init.getFromDisk(storage, file, attachment, run);
        }
      });
  };

我的问题是我可以捕获404 好吧,但是我不想返回error 对象,而是返回init.getFromDisk 生成的承诺。

问题
是否可以在错误处理程序中返回我的getFromDisk 调用的结果?如果不是,我将如何构建我的调用,以便我总是向我的第一个方法调用返回一个承诺?

感谢您的帮助!

解决方案
谢谢您的帮助!像这样修复它:

 init.fetchConfigurationFile(
      storage,
      "gadgets",
      gadget.getAttribute("data-gadget-id"),
      pointer
    ).always(function(fragment) {
      console.log("gotcha");
      console.log(fragment);
    });

init.fetchConfigurationFile = function (storage, file, attachment, run) {
  return storage.getAttachment({"_id": file, "_attachment": attachment})
    .then(function (response) {
      return jIO.util.readBlobAsText(response.data);
    })
    .then(
      function (answer) {
        return run(JSON.parse(answer.target.result));
      },
      function (error) {
        if (error.status === 404 && error.id === file) {
          return init.getFromDisk(storage, file, attachment, run);
        }
      }
    );
};

【问题讨论】:

  • 为什么是.then(...).then()?尝试删除第一个.then() 并将第二个.then() 的第一个回调更改为function (response) { var answer = jIO.util.readBlobAsText(response.data); return run(JSON.parse(answer.target.result)); }。净效应应该是相同的。
  • 同意。目前它只适用于then().then(),因为我使用的插件需要这种语法。我已经向作者(同事)提过一个then() 会让事情变得更容易。
  • 好的,.then().then() 可以正常工作,但简化为 .then() 会更易读(我相信你已经知道了)。

标签: javascript jquery ajax promise jquery-deferred


【解决方案1】:

.fail() 总是返回原始承诺。

您应该使用失败回调调用then() 以允许链接:

.then(undefined, function(error) {
    return ...;
});

在 jQuery 1.8 之前,请改用.pipe()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2018-04-10
    • 2020-02-10
    • 2021-02-11
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多