1

我有一个创建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);
  });

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);
        }
      }
    );
};
4

1 回答 1

3

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

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

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

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

于 2013-10-08T16:48:58.453 回答