繁体   English   中英

如何在Javascript / Jquery中对失败的ajax请求返回新的promise而不是错误?

[英]How to return a new promise instead of an error on a failed ajax request in Javascript/Jquery?

我有一个创建deferred对象的函数。 fail我正在调用一个回退函数,后者又创建并返回它自己的deferred/promise对象。 我想返回这个后备 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);
  });

如果我需要的文档/附件不在localstorage中,我的fetchConfiguration调用会尝试从localstorage加载并从文件加载回退。

  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 allright,但我不想返回error对象,而是返回init.getFromDisk生成的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);
        }
      }
    );
};

.fail()始终返回原始承诺。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM