代码之家  ›  专栏  ›  技术社区  ›  Jimmy

如果我们得到某个结果,重试函数承诺

  •  1
  • Jimmy  · 技术社区  · 6 年前

    我就快成功了。这段代码查询API以返回reportID,然后使用reportID再次查询它以获取数据。

    function myfunction(ref) {
      getReport(ref, "queue", "hour", "2018-10-03", "2018-10-04", "pageviews", "page").done(function(r1) {
        getReport(r1.reportID, "get").done(function(r2) {
          if (r2.error == "report_not_ready") {
            console.log("Not ready");
            setTimeout(function() {
              myfunction(ref)
            }, 1000);
          }
          console.log(r2);
        })
      });
    }
    
    
    function getReport(ref, type, granularity, from, to, metric, element) {
      return $.getJSON("report.php", {
        ref: ref,
        type: type,
        granularity: granularity,
        from: from,
        to: to,
        metric: metric,
        element: element,
      });
    }
    

    这段代码的问题是,有时当我们尝试获取报表时,报表还没有准备好,所以我们需要稍后重试。如果返回not ready(包括生成一个新的报告ID),我现在的代码会再次运行整个报告。

    它要做的只是重试原始的reportID。

    有人能帮我理解怎么做吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Anurag Awasthi    6 年前

    function reportHandler(id, r2, retries){
        if(retries >= 3){
            console.log("tried 3 times")
            return
        }
        if (r2.error == "report_not_ready") {
            console.log("Not ready");
            setTimeout(function() {
              getReport(id, "get").done(r2=>reportHandler(id, r2, retries + 1))
            }, 1000);
          }
          console.log(r2);
    }
    
    function myfunction(ref) {
      getReport(ref, "queue", "hour", "2018-10-03", "2018-10-04", "pageviews", "page").done(function(r1) {
        getReport(r1.reportID, "get").done(r2=>reportHandler(r1.reportID, r2, 0))
      });
    }
    
        2
  •  1
  •   CodingNagger    6 年前

    从代码看来,您只需要重新获取 r2

    function myfunction(ref) {
        getReport(ref, "queue", "hour", "2018-10-03", "2018-10-04", "pageviews", "page").done(function (r1) {
            getReportFromId(r1.reportID);
        });
    }
    
    function getReportFromId(reportId) {
        getReport(reportId, "get").done(function (r2) {
            if (r2.error == "report_not_ready") {
                console.log("Not ready");
                setTimeout(function () {
                    getReportFromId(reportId)
                }, 1000);
            }
            console.log(r2);
        })
    }
    
    function getReport(ref, type, granularity, from, to, metric, element) {
        return $.getJSON("report.php", {
          ref: ref,
          type: type,
          granularity: granularity,
          from: from,
          to: to,
          metric: metric,
          element: element,
        });
    }