0

I'm trying to get the text from the response body to a request into a global variable.

var Request = require('request');

var result = "Not set";                

var foodrequest = Request({ uri: url }, function (error, response, body) {
            result = body;
});

console.log(result);

the "result" variable however is not set correctly.

How can I achieve this?

1 Answers1

0

That's because the callback for Request is called asynchronously, while whatever is found after the invokation of the function named Request is executed (let me say) synchronously.
That means that the console.log statement has no chance to be executed after the callback.
So, when you reach the console.log statement, the above mentioned function has not been invoked yet.

skypjack
  • 49,335
  • 19
  • 95
  • 187