0

I'm running the following within node.js:

function makeGetFunction(url) {
 url = url + '?' + authstring;
    console.log("get " + url);
    request.get(url, function(e, r, data) {
        var json = JSON.parse(data);
        var resp = json.entities;
    });
}

I would like to have makeGetFunction() return resp. I think the the answer lies somewhere with using a callback, but as I'm fairly new to asynchronous calls in javascript, I'm stumbling with how to properly pull it off. I haven't been able to find any examples or posts related to my question yet. Please excuse the newbie question.

user3393335
  • 1
  • 1
  • 3
  • Upon returning resp, it appears to be empty. I'm not sure, but perhaps when it returns request hasn't yet come back? – user3393335 Aug 24 '14 at 15:48
  • Please read [How to return from async function](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function). – Viktor Bahtev Aug 24 '14 at 16:05

1 Answers1

0

Since the procedure involves asynchronous calls, the best choice is to follow the same pattern in makeGetFunction, by adding a callback argument:

function makeGetFunction(url, callback) {
 url = url + '?' + authstring;
    console.log("get " + url);
    request.get(url, function(e, r, data) {
        var json = JSON.parse(data);
        var resp = json.entities;
        callback(resp);
    });
}

When using makeGetFunction, pass it a handler function instead of retrieving the return value:

makeGetFunction('www.myurl.net/what', function(resp) {
    // do stuff with response
});
E_net4
  • 27,810
  • 13
  • 101
  • 139
  • Thanks--that did it! And, now I think I have a slightly better understanding of async and callbacks... – user3393335 Aug 24 '14 at 16:21
  • Glad to know that you understand it now. You may also want to consider passing more arguments to the callback function, such as an error object if applicable (conventionally, as the first argument). – E_net4 Aug 24 '14 at 16:24