如何重新构造javascript函数以在不同的函数中输出数据
我想知道你是否能帮我。我有一些代码,我一直在努力重组。这就是它现在的样子:如何重新构造javascript函数以在不同的函数中输出数据,javascript,jquery,Javascript,Jquery,我想知道你是否能帮我。我有一些代码,我一直在努力重组。这就是它现在的样子: function myfunction(ref) { getReport(ref, "queue", "hour", "2018-09-03", "2018-10-04", "pageviews", "page").done(function(r1) { getReport(r1.reportID, "get").done(r2=>reportHandler(r1.reportID, r2, 0))
function myfunction(ref) {
getReport(ref, "queue", "hour", "2018-09-03", "2018-10-04", "pageviews", "page").done(function(r1) {
getReport(r1.reportID, "get").done(r2=>reportHandler(r1.reportID, r2, 0))
});
}
function reportHandler(id, r2, retries){
if(retries >= 3){
console.log("Retried 3 times - stopping")
return
}
if (r2.error == "report_not_ready") {
console.log("Not ready");
setTimeout(function() {
getReport(id, "get").done(r2=>reportHandler(id, r2, retries + 1))
}, 2000);
}
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,
});
}
我还没有弄清楚的是如何处理数据,这是我想在myfunction中实现的
目前我唯一能做的就是在我的报表处理函数中返回数据
我希望能够在myfunction函数中从API返回数据,然后进一步处理数据,然后使reporthander和getreport函数保持通用 我相信你的问题就在这里:
getReport(r1.reportID, "get").done(r2=>reportHandler(r1.reportID, r2, 0))
$.getJSON()
作为一种承诺,而.done()
在功能上与.then()
相同。这两种方法都接受函数作为参数,但传递函数的方式并不正确。通过向函数传递参数而不仅仅是其名称,您告诉JavaScript运行函数并使用其结果——这不是您想要的。在您的情况下,最简单的修复方法是:
getReport(r1.reportId, "get").done((r2) => { reportHandler(r1.reportId, r2, 0); });
或者,如果您能够使用新的async/await语法,则可以使其更简单:
const r2 = await getReport(r1.reportId, "get");
const handler = await reportHandler(r1.reportId, r2, 0);
// and so on
这有意义吗?如果您还有什么不明白的,请告诉我们
编辑:好的,根据这个答案上的注释,正在运行的代码结构正确,如下所示:
function myfunction(ref) {
getReport(ref, "queue", "hour", "2018-09-03", "2018-10-04", "pageviews", "page").done(function(r1) {
getReport(r1.reportId, "get").done((r2) => {
reportHandler(r1.reportId, r2, 0);
});
});
}
因此,我能想到的唯一答案是myFunction()
中的第一个getReport()
调用没有返回主体中带有reportId
的对象。运行此代码时,您是否遇到任何未捕获的错误
编辑2:根据注释,由于大写错误,属性被错误引用。当响应返回
r1.reportId
时,代码正在调用r1.reportId
使用then
而不是done
进行管道输出。@plalx这是一个好主意,但我似乎没有为此使用正确的语法。您好,谢谢。我试图把它放在一起,它看起来是这样的:function myfunction(ref){getReport(ref,“queue”,“hour”,“2018-09-03”,“2018-10-04”,“pageviews”,“page”).done(function(r1){getReport(r1.reportId,“get”).done((r2)=>{reportHandler(r1.reportId,r2,0);};}
但是它似乎没有将报告ID传递给整个系统。您是否确认了getReport()
函数返回的结果正确?您可以通过放置console.log(r1)来实现这一点代码>在回调中,在第二次调用之前。也就是说,我想知道第一个调用是否返回了一个带有reportId
属性的对象。您的原始帖子缺少reportHandler()
周围的花括号,因此我不确定您的原始代码中是否包含这些内容。检查你的代码,确保它们在那里。我马上在这里编辑我的答案。实际上,我想我已经在一秒钟内发现了这个问题。reportID中必须有大写字母D,这是唯一的问题