0

I hope this is not a duplicate. So far I could find a few tutorials and questions about this - but usually everyone just wants to log the results of their code to console, which is not helping me.

I want to fetch some data from an API to plot it on a website.

The fetching seems to work fine, because I can log the results inside the fetch.then() to the console, but (obviously) they do not make their way outside of the fetch.

The only solution I was able to find is to wrap this whole thing in another function or to write a function that works with the data fetched inside of the.then().

I couldn't make the first idea work, because I cannot return anything for the same reason as above (the data does not make it's way outside of the .then()).

The second one is problematic, because I simply want to plot the results from a few .json entries to a Plotly plot. And I have honestly no idea how to place this inside of a function.

// 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) 
*/
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

Maybe you can try to separate your fetch and return the data to a function where you use the data to do what you want. You can try something like this - I think it is the same as what other people commented.

//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();

Take at look at this link if you get stuck.