简体   繁体   中英

Accessing populated variable outside of function scope js

var JsonObj = {};
if (Titanium.Network.online) {
  apiHelper.APIPostRequest(APIURL + '/it', tempJSON, function(e) {
    var status = this.status;
    if (status == 200) {
      JsonObj = JSON.parse(this.responseText);
      //behaves as expected
      //console.log(JsonObj);           
    }
  }, function(err) {
    alert('Unknown error from api');
  });
} else {
  alert('No internet connection found');
}
console.log(JsonObj);

When I print it out of the function scope, it returns an empty json object, if I do it within the function it populates it with the relevant data.

I have created a very simple JS file, testing the scope problem and it works:

var i=5;

if(i>3){

    if(i>4)
    {


      i = 6;  

    }

}

alert(i);

This has most likely nothing to do with your function scopes.

In most common scenarios with issuing request, you do in asynchronously, that means your console.log executes right after you have issued the request, the function you provide inside the request only executes when you get a response... (Async)

Hence at the time you write out your object at the bottom, the object has not yet been set. As the callback function has not yet been executed.

I highly expect that the apiHelper.APIPostRequest lives up to this pattern. But since I don't have knowledge of any of those frameworks I can't say for sure, but with they way you also describe the error... It's the only obvious thing i can see.


var JsonObj = {};
console.log("Before Async Request: " + JsonObj);
if (Titanium.Network.online) {
  apiHelper.APIPostRequest(APIURL + '/it', tempJSON, function(e) {
    var status = this.status;
    if (status == 200) {
      JsonObj = JSON.parse(this.responseText);
      console.log("Inside Async Callback: " + JsonObj);
      //behaves as expected
      //console.log(JsonObj);           
    }
  }, function(err) {
    alert('Unknown error from api');
  });
} else {
  alert('No internet connection found');
}
console.log("After Async Request: " + JsonObj);

You may as well start to learn about Promises right away... Eg with Q it should go something like this:

var deferred = Q.defer(),
    JsonObj = deferred.promise;
if (Titanium.Network.online) {
  apiHelper.APIPostRequest(APIURL + '/it', tempJSON, function(e) {
    var status = this.status;
    if (status == 200) {
      deferred.resolve(JSON.parse(this.responseText));
    }
  }, function(err) {
    deferred.reject(err);
  });
} else {
  alert('No internet connection found');
}

JsonObj.then(function(json) {
  console.log("After Async Request: " + json);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM