Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

186
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda