2

Async JS is not my thing.

I have something that looks like this:

function GetData() {
    http.get(options, function (error, response, body) {
        return JSON.stringify(body.results[0].members);
    });
}
var list = GetData();
console.log(list);

This of course does not work. list is "undefined," presumably because console.log runs before GetData has a chance to return. I've been struggling way too long with this. Is there a short, simple fix?

Jimmy D
  • 5,282
  • 16
  • 54
  • 70
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Muhammad Usman Jan 09 '20 at 10:53
  • Have a look at this page: https://usefulangle.com/post/170/nodejs-synchronous-http-request – Nicola Lepetit Jan 09 '20 at 10:55

3 Answers3

3

Pass callback as parameter or create Promise. This is callback example

function GetData(callback) {
    http.get(options, function (error, response, body) {
        callback(JSON.stringify(body.results[0].members));
    });
}
GetData(function(list){
  console.log(list)
})
Sargis Isoyan
  • 1,049
  • 8
  • 15
2

you can use async-await and return a promise from your function GetData

function GetData() {
  return new Promise((resolve, reject) => {
    http.get(options, function (error, response, body) {
        if(!error) resolve(JSON.stringify(body.results[0].members));
        else reject(error);
    });
  });
}
var list = await GetData();
console.log(list);

don't forget to use async in the function where we are using await GetData();

Yogesh.Kathayat
  • 974
  • 7
  • 21
0

your problem isn't that it's async but you're returning inside the function of the http.get callback.

function GetData(callback) {
    http.get(options, function (error, response, body) {
        callback(JSON.stringify(body.results[0].members));
    });
}
var callback = function (a) {console.log(a);};
GetData(callback);

Joost K
  • 1,096
  • 8
  • 23