0

I want to save the body from a get request in a variable (using the request module), but its undefined.

I've searched for a solution but nothing worked so far. Guess the problem is that request.get is calles async (so far i have no experience in async functions).

const request = require("request")
...
let foo;
request.get(options,function(err,response,body){
    foo = body;
});
console.log(foo);

expected: the body of the valid get-request actual: undefined

marioweid
  • 3
  • 1

1 Answers1

0

The request is done in asynchronous way so your console.log happens before the request is completed, so foo is still undefined.

You must put your console log inside the callback body. Also, any computation requiring the result from the request should be started from within the callback.

request.get(options,function(err,response,body){
    console.log(body);
    doSomethingAfterMyRequest(body)
});

Also, you should handle your error, because if an error occurs during your request, it's possible that body remains undefined.

request.get(options,function(err,response,body){
    if (err) {
        console.error(err)
        return
    }
    console.log(body);
    doSomethingAfterMyRequest(body)
});
Francois
  • 3,050
  • 13
  • 21