簡體   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