Using HTTP call method to set parameters in response

Hello,

I am currently using the HTTP.call() method to call a webservice and process the response.
After doing the call, I am trying to use the response object to fill in (initialize) some variables, but it seems that doesn’t really happen.

Can anyone please explain how that happens and how I can make this work? Please see code below:

    let testString;
    HTTP.call('GET','http://localhost:8080/getinformation', {
        params: {
            "userid": user._id,
            "locationid": locationid,
        }
    },function(error, response) {
        if(error) {
            console.log("Error -> " + error);
            testString = error;
        } else {
            testString = response.statusCode;
        }
    });
    console.log('TEST STRING -> ' + testString);

Calling Test string in the console log, returns an undefined.

That’s normal JavaScript behaviour. The HTTP request is asynchronous, so its response is only available through the callback. The code after the HTTP request executes synchronously:

console.log('a');
HTTP.call('...', (error, response) => {
  console.log('b');
});
console.log('c');

Logs: a, c, b.

If you are doing this on the server, you can use the non-callback form and it will work as you expect:

try {
  let testString = HTTP.call('GET', 'http://localhost:8080/getinformation', {
    params: {
      "userid": user._id,
      "locationid": locationid,
    }
  });
  console.log('TEST STRING -> ' + testString);
} catch (error) {
  //...
}

That did the trick! Thanks a lot!

1 Like