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

188
Visualizações
How to return data from http.get to parent function in nodejs

Task is to return data from getData function to main function.

function getData(){
    const https = require('https')
    const url = "https://...../api/movies";
    https.get(url, res => {
      let data = '';
      res.on('data', chunk => {
        data += chunk;
      });
      res.on('end', () => {
        data = JSON.parse(data);
        console.log(data);
        //How can I return this data to main function?
      })
    }).on('error', err => {
      console.log(err.message);
    })
}
function main(){
    console.log(getData());
}

I am not able to access data or print data in main function

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

I think you already have the answer in your comment '//How can I return this data to main function?'.

...
res.on('end', () => {
        data = JSON.parse(data);
        console.log(data);
        return data;
      })
...

So the return-value of your getData-function should now be the parsed json-data and be accessible in the main-function.

about 4 years ago · Juan Pablo Isaza Relatório

0

I would create a variable to save value which you want to return

const https = require('https')

function getData() {
    let ret = null;
    
    const url = "https://...../api/movies";

    https.get(url, res => {
      let data = '';
      res.on('data', chunk => {
        data += chunk;
      });
      res.on('end', () => {
        ret = JSON.parse(data);
      })
    }).on('error', err => {
      console.log(err.message);
    })
    
    return ret;
}

function main() {
    console.log(getData());
}
about 4 years ago · Juan Pablo Isaza Relatório

0

What you could do is to wrap your request into a Promise. You would want to return this promise and and wait for it to be fullfilled:

function getData() {

    const url = "https://...../api/movies";

    return new Promise((resolve, reject) => {
        const req = https.get(url, (res) => {
            let data = '';

            res.on('data', (chunk) => {
                data += chunk;
            });

            res.on('end', () => {
                resolve(JSON.parse(data));
            });
        });

        req.on('error', (err) => {
            reject(err);
        });

        req.end();
    });
}

function main() {
    getData().then(data => {
        console.log("Response:", data);
    }, error => {
        console.error(error);
    });
}

Moreover you can make your main function async and use await to get the response:

async function main() {
    const data = await getData();
    console.log(data);
}

// Start an IIFE to use `await` at the top level. See: https://stackoverflow.com/a/14220323/7661119
(async () => {
    await main()
})();
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