Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
Fetch API data for plotly in Javascript

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) 
                    */
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda