Javascript 在其他函数中减少

Javascript reduce in other function

如何通过 reduce 函数将我从 JSON 文件解析到 运行 的数据获取到 运行 以消除重复项,然后通过调用 getFiilteredData() 函数使其可用?

async function getFilteredData() {
        return new Promise((resolve) => {
          oWebViewInterface.on("loadData", function (data) {
            var schwellWerte = data.monitor;
            var monitorData = data.data.reduce((arr, d) => {
              if (arr.find((i) => i.zeitstempel === d.zeitstempel)) {
                return arr;
              } else {
                return [...arr, d];
              }
            }, []);
            resolve(monitorData); // resolve the promise with the data
            //can I do: resolve(monitorData, schwellWerte) to resolve both?
          });
        });
      }

这样做会导致最后两个 console.log() 出现“Uncaught TypeError: Cannot read 属性 '0' of undefined”,但第一个工作正常并记录预期值。

最简单的方法是使用 Promise 和 async/await。将您的异步调用包装在 Promise 中并在客户端等待它:

async function getFilteredData() {
    return new Promise( resolve => {
        oWebViewInterface.on("loadData", function (data) {
          var monitorData = JSON.parse(data).reduce((arr, d) => {
            if (arr.find((i) => i.zeitstempel === d.zeitstempel)) {
              return arr;
            } else {
              return [...arr, d];
            }
          }, []);
          resolve(monitorData); // resolve the promise with the data
        });
    });
}

然后当你调用它时 await 调用

var filteredData = await getFilteredData();
console.log(filteredData[0].id);

编辑:我从您的评论中注意到,在您的代码中您调用了两次 getFilteredData - 这似乎是个坏主意。调用一次。如果您将图表的配置放入它自己的 async 方法中,这会变得更容易

async function configChart(){
      var data = await getFilteredData();
      var werteArr = [];
      var zsArr = [];
      for (i = 0; i < data.length; i++) {
         werteArr.push(data[i].wert);
         zsArr.push(data[i].zeitstempel);
      }
        

      //defining config for chart.js
      var config = {
        type: "line",
        data: {
          labels: zsArr ,
          datasets: {
            data: werteArr,
            // backgroundcolor: rgba(182,192,15,1),
          },
        },
        // -- snip rest of config -- //
     }
     var ctx = document.getElementById("canvas").getContext("2d");
     window.line_chart = new window.Chart(ctx, config);
}

window.onload = function () {
    configChart(); // no need to await this. It'll happen asynchronously
};