我非常接近完成这项工作。此代码查询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。
有人可以帮助我了解如何执行此操作吗?
答案 0 :(得分: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))
});
}
答案 1 :(得分: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,
});
}
这样,您的重试仅涵盖第二次检索。