1

我非常接近让这个工作。此代码查询 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,
  });
}

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

它的意思是重试原始reportID。

谁能帮我理解如何做到这一点?

4

2 回答 2

1

以下代码调用 api 3 次然后退出,

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))
  });
}
于 2018-10-09T12:54:20.570 回答
1

从代码看来,您只需要重新获取 的结果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,
    });
}

这样,您的重试仅涵盖第二次检索。

于 2018-10-09T12:57:47.860 回答