首页 > 解决方案 > 在 Javascript 中为 plotly 获取 API 数据

问题描述

我希望这不是重复的。到目前为止,我可以找到一些关于此的教程和问题 - 但通常每个人都只想将他们的代码结果记录到控制台,这对我没有帮助。

我想从 API 中获取一些数据以将其绘制在网站上。

获取似乎工作正常,因为我可以将 fetch.then() 中的结果记录到控制台。但是(显然)他们并没有在获取之外进行。

我能找到的唯一解决方案是将整个事情包装在另一个函数中,或者编写一个函数来处理从 .then() 中获取的数据。

我无法使第一个想法奏效,因为出于与上述相同的原因,我无法返回任何内容(数据不会使其超出 .then() 的范围)。

第二个是有问题的,因为我只是想将一些 .json 条目的结果绘制到 Plotly 图中。老实说,我不知道如何将它放在一个函数中。

                    // Arrays for results
                    var sugars = [];
                    var times  = [];
            
                    // fetch the BG data from the API and write results into arrays
                    fetch(url)
                        .then((resp) => {return resp.json()})
                        .then(  (result) => {
                                // read glucose values from json
                                // logging the results/sugars/times to console from here works!
                                for (let i = 0; i < n_entries; i++) {sugars[i] = result[i]["sgv"]}
                                for (let i = 0; i < n_entries; i++) {times[i]  = -i * timestep} 
                        });

                    var x1;
                    var y1;
                    
                    /*
                    // Dummy data to test plotly, these WORK for some reason.
                    x1 = [0, -5, -10, -15, -20];
                    y1 = [123, 119, 113, 107, 102];
                    */
                
                    // These values, however, don't work:
                    /*
                    x1 = times;
                    y1 = sugars;
                    
                    // this yields 'undefined' errors:
                    console.log(times) 
                    */

标签: javascriptapiasynchronousfetchplotly.js

解决方案


也许您可以尝试分离您的 fetch 并将数据返回给您使用数据做您想做的事情的函数。您可以尝试这样的事情-我认为这与其他人的评论相同。

//make the fetch and return response data as json
async function getData() {
    let url = 'your url';
    try {
        let resp = await fetch(url);
        return await resp.json();
    } catch (error) {
        console.log(error);
    }
}

//do whatever you want with the data response
async function myFunc() {
    let data = await getData();

    //do some stuff with your data here
}

//call the function
myFunc();

如果您遇到困难,请查看此链接。


推荐阅读