首页 > 解决方案 > 无法显示标记。setMarkers() 函数返回 TypeError: t.map is not a function

问题描述

我查看了 github 上的文档,但找不到更多关于标记的信息。这是他们给出的示例: https ://github.com/tradingview/lightweight-charts/blob/ef8cfa40cb51ee1f9a5c11bd099bc510c022b010/docs/series-basics.md#setmarkers

我似乎有正确的标记数组,但没有运气。

async function getCandle() {
    while(true){
        await fetch('localhost:5000/candle.json')
        .then(res => res.text())
        .then(data => {
            /* Handling of data */
            candleSeries.setMarkers(getMarkers()); // returns TypeError: t.map is not a function at i.t.setMarkers
            // chart.setMarkers(getMarkers()); returns TypeError: chart.setMarkers is not a function
        })
        await sleep(1000);
    }
}

async function getMarkers(){
    await fetch('http://localhost:5000/markers.jsonl')
    /* markers.jsonl looks like this:
    {"time": 1592913600, "position": "belowBar", "shape": "arrowUp", "color": "green", "id": 1, "text": "BUY"}
    {"time": 1592913900, "position": "belowBar", "shape": "arrowUp", "color": "green", "id": 1, "text": "BUY"}
    */
    .then(res => res.text())
    .then(data => {
        data = data.split("\n");
        let markers = data.map(d => {
            // Parse d from string to JSON
            d = JSON.parse(d);
            return {time: d["time"], position: d["position"], shape: d["shape"], color: d["color"], id: d["id"], text: d["text"]}
        });
        return markers;
    })
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

标签: javascriptmarkerstradingview-apilightweight-charts

解决方案


getMarkers是异步函数,Promise如果你不这样做,它会返回一个实例await

您需要将数据处理程序标记为async函数和await getMarkers结果:

async function getCandle() {
    while(true){
        await fetch('localhost:5000/candle.json')
        .then(res => res.text())
        .then(async (data) => {
            /* Handling of data */
            candleSeries.setMarkers(await getMarkers());
        })
        await sleep(1000);
    }
}

编辑(来自@Nipheris 评论):你没有从函数返回任何东西getMarkers,所以你需要在return那里添加语句。


推荐阅读