0

This is really a question around Javascript scope and functions so I apologise as I'm a newbie to JS!!

I have a snippet of javascript, that connects creates a HTTPClient connection to a REST service from Vertx - this all works fine no issues here.

My problem is that I need access to the "status" and "data" returned from the "client.request" outside of this call

// Create the HTTP Client
var client = vertx.createHttpClient().host(host).port(ssl_port).ssl(true);


var request = client.request("POST", "/api/en/v1.0/authentication/token/new" + "?login_id=" + login_id + "&api_key=" + api_key, function(resp) {

    //console.log("Got a response: " + resp.statusCode());
    resp.bodyHandler(function(body) {
        // Parse the JSON string into a new object.
        var response = JSON.parse(body);
        console.log("status : " + response.status);
        console.log("data : " + response.data);
    })
});


request.end();

So in code down here I'd like to use/access "status" and "data". In another language I'd just return them as an object up the call stack.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318

3 Answers3

1

Store them in a variable outside the of function and you have access to it. If you need to know when the information is available, define a callback function or take a look at javascript custom events.

Daniel
  • 601
  • 1
  • 4
  • 13
1

You can do the same thing in javascript as well. Refer this document.

You can create a class:

function httpResponse(status,data) {
this.status=status;
this.data=data;
}

Set values like:

var myStatus = new httpResponse(response.status, response.data);

Add return statement:

return myStatus;

In your calling code you can access this data as:

var status = myStatus.status;
Akshay
  • 350
  • 1
  • 7
-1

Define a global variable outside the function.

var myVariable1_status;
var myVariable1_data;

Then assign the status and data-value to the variables inside the function.

function(){
    myVariable1_status = status;
    myVariable1_data = data;
}
Solders
  • 391
  • 1
  • 4
  • 11