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

如何重构javascript函数以不同的函数输出数据

  •  0
  • Jimmy  · 技术社区  · 7 年前

    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函数的通用性。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jpec07    7 年前

    我相信你的问题就在这里:

    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); });
    

    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);
        });
      });
    }
    

    getReport() 呼叫内部 myFunction() 不返回具有 reportId 在身体里。当这个代码运行时,您是否有任何未捕获的错误?

    编辑2:根据注释,由于大写错误,属性被错误引用。代码要求 r1.reportId r1.reportID .