在forge dataviz api上使用异步回调

wgmfuz8q  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(369)

在尝试使用新的forge datavisualization api将自定义数据添加到热图中时,我遇到了一些问题,即尝试使用异步函数将数据链接到热图。
我想在 getSensorValue 回拨。如果我只返回一个math.random(),它会工作:

function getSensorValue(surfaceShadingPoint, sensorType) {

        return Math.random();
    }

但每当我尝试添加任何可等待的函数时,它都不会渲染任何表面着色:

[...]
     function normalizeValue(value, min, max) {
        return (value - min) / (max - min);
    }

     async function getSensorValue(surfaceShadingPoint, sensorType) {
        let data = await asynchronousFunction();
        data = data[data.length-1]
        let temperature = (data[0].temperature);
        return normalizeValue(temperature,19,37);
    }
[...]

    setInterval(async function () {
        const floorName = 'A1_Level 1';
        dataVizExt.renderSurfaceShading(floorName, sensorType, await getSensorValue);
    }, 1000);

我也尝试过这样的承诺,但没有成功…:

function getSensorValue(surfaceShadingPoint, sensorType) {
        return (promise = new Promise((resolve, reject) => {
            resolve(asynchronousFunction());
        }));
    }
    function normalizeValue(value, min, max) {
        return (value - min) / (max - min);
    }

    setInterval(function () {
        const floorName = 'A1_Level 1';
        dataVizExt.renderSurfaceShading(floorName, sensorType, () =>
            getSensorValue().then((res) => {
                let data = res;
                data = data[data.length - 1];
                let temperature = data.temperature;
                return normalizeValue(temperature,22,40);
            })
        );
    }, 1000);

我是否对api有任何误解,或者我是否弄乱了js异步逻辑?

q9rjltbz

q9rjltbz1#

好吧,我成功了。这不是最优雅也不是最漂亮的解决方案,但它确实有效。

//function that gets the data and formats it for the heatmap
async function getSensorValue() {
    let data = await asynchronousFunction();
    data = data[data.length - 1];
    let temperature = data.temperature;
    return normalizeValue(temperature,22,40);
}
//global variable that holds the last temperature value from the server
var normalizedValue;
//non async function that just returns the global variable. 
//(It has to be function because the API expects it as a callback)
function getVar(surfaceShadingPoint, sensorType){
    return normalizedValue;
  }
//function that normalizes any value between 2 numbers
function normalizeValue(value, min, max) {
    return (value - min) / (max - min);
}
//interval that tries to get new data from the server each X seconds.
setInterval(async function () {
    normalizedValue = await getSensorValue();  
    if(normalizedValue){         
        const floorName = 'A1_Level 1';
        dataVizExt.renderSurfaceShading(floorName, sensorType, getVar)
    }
}, 2000);

我不知道什么时候或者是否能够在dataviz扩展的这个特定端点上使用async函数,但这就完成了我现在需要的工作。

相关问题