-1

I'm doing a JSON call like this:

var desc = getItemDescriptions(xxx);

function getItemDescriptions(xxx) {
var url = "xxx;
var info = {};

request({
url: url,
json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {
        info ["..."] = body.result[xxx].yyy;
        info ["..."] = body.result[xxx].yyy;
        info ["..."] = body.result[xxx].yyy;
        info ["..."] = body.result[xxx].yyy;
        info ["..."] = body.result[xxx].yyy;
    }
})
return info;
}

My Problem is, the JSON request need some time to get response back... and my function doesn't wait for this response. The Function returns the empty array without waiting.

How can i wait for response and then return the filled array?

thx

lhuber
  • 403
  • 1
  • 3
  • 13
  • 3
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – JJJ Apr 26 '15 at 10:45
  • what framework are you using? where is the "request" function defined? – navotgil Apr 26 '15 at 10:46
  • @navotgil https://www.npmjs.com/package/request – lhuber Apr 26 '15 at 10:46
  • Add an event-trigger when the request is done, perhaps? The listen for that and executen on triggered. – mcmhav Apr 26 '15 at 10:49
  • from npm docs: request.get('http://google.com/img.png').on('response', function(response) { console.log(response.statusCode) // 200 console.log(response.headers['content-type']) // 'image/png' }) – navotgil Apr 26 '15 at 11:04

2 Answers2

0

Its not like executing fast, it is the way javascript runs statement after statement. To get the data you need to do that in success callback function, the data would be available only when the server response comes back as its asynchronous call by the time response comes your javascript executes next statements.

vinayakj
  • 5,591
  • 3
  • 28
  • 48
0

Juhana already linked to you the best place to get a good solution. How to return the response from an async call

A quick and dirty hack would be (if request is a jQuery-like Ajax-function) to make the request synchronus.

This might be done by adding async: false to the first parameter passed to request:

request({ url: url,json: true, async: false}, function ....

That way return info will be executed AFTER your request has finished.

HTH Georg

Community
  • 1
  • 1
Georg Mavridis
  • 2,312
  • 1
  • 15
  • 23