Javascript减少其他功能

问题描述

如何从JSON文件中解析的数据通过reduce函数运行以消除重复项,然后通过调用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()出现“未捕获的TypeError:无法读取未定义的属性'0'”,但第一个可以正常工作并记录期望值。

解决方法

最简单的方法是使用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
};