【问题标题】:Can't display markers. setMarkers() function returns TypeError: t.map is not a function无法显示标记。 setMarkers() 函数返回 TypeError: t.map 不是函数
【发布时间】:2020-10-14 01:15:50
【问题描述】:

我查看了 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));
}

【问题讨论】:

    标签: javascript markers tradingview-api lightweight-charts


    【解决方案1】:

    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 语句。

    【讨论】:

    • 感谢您的回答。但是,我这样做了,现在我得到了以下信息:TypeError: Cannot read property 'map' of undefined at i.t.setMarkers
    • @Zamo 你能简化你的代码并分享它吗?我的意思是,这样每个人都可以在本地运行它并帮助你。例如,在 jsfiddle 上。
    • @Zamo 你的getMarkers 函数没有返回任何内容,难怪setMarkers 函数从getMarkers 接收undefined。也许把它改造成这样的东西? async function getMarkers() { const response = await fetch('http://localhost:8000/markers.jsonl'); const responseText = await response.text(); return responseText.split("\n").map(JSON.parse); }
    • @Nipheris 我以为我在 getMarkers() 中返回了标记,但我想我错了。我不知道你可以像你一样写它(在我的辩护中,我只使用了 JS 5 天)。谢谢,现在可以了。如何将您的评论设置为解决方案?我是新来的,所以
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-01
    • 2013-09-24
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2018-05-09
    • 2018-01-22
    相关资源
    最近更新 更多