Home > Mobile >  How to return data from http.get to parent function in nodejs
How to return data from http.get to parent function in nodejs

Time:05-25

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

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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()
})();
  • Related