javascript - Assigning a Value? -


i have following code in services.js/cordova

.factory('gcs', ['$http', function($http) {         var obj= {};          $http.post("mydomina.com?myrequest=getbyid", { "id": "1"} )             .success(function(data) {                obj= data; //there data returned correctly db             })             .error(function(data, status, headers, config) {                 return null;             });             console.log(obj); //obj undefined?         return {             all: function() {               return obj;             }         };     }]); 

i trying return json array (obj) database, however, obj undefined , thereby returning null in method (all) can tell me reason why?

thanks

you running issues you're mixing synchronous , asynchronous code. it's made more complicated fact you're letting variable used asynchronous callback visible external synchronous code.

consider happening in example code.

function foo() {     var bar = false;     settimeout(function () {         bar = true;         console.log(bar); // logs true     }, 1000);     console.log(bar); // logs false     return {         buzz: function () {             return bar;         }     }; }  // see have var fizz = foo(); // console.log(fizz.buzz()); // logs false // .. wait >1 second settimeout(function () {     console.log(fizz.buzz()); // logs true }, 1500); 

the settimeout in foo here similar .success or .error in code

so solutions problem?

  • use asynchronous callback invoke subsequent pieces of code
  • fire event callback , listen event before continuing other pieces of code (you may have implement custom version of event listeners/handlers depending on environment)

here example of implementing events manually, may bit overkill needs

function objectwithevents(obj) {     var handlers = object.create(null);     if (!obj) {         if (this instanceof objectwithevents) obj = this;         else return new objectwithevents();     }     object.defineproperty(obj, 'addeventlistener', {         value: function (type, handler) {             if (!(type in handlers)) handlers[type] = [];             handlers[type].push(handler);         }     });      object.defineproperty(obj, 'removeeventlistener', {         value: function (type, handler) {             var i;             if (!(type in handlers)) return;             = handlers[type].indexof(handler);             if (i !== -1) handlers[type].splice(i, 1);         }     });      object.defineproperty(obj, 'dispatchevent', {         value: function (e) {             var i, j, frozen_handlers;             if (!(e.type in handlers)) return;             frozen_handlers = handlers[e.type].slice();             j = frozen_handlers.length;             (i = 0; < j; ++i) {                 frozen_handlers[i].call(this, e);                 // if (e.cancelled) return;             }         }     }); } objectwithevents.prototype = object.create(object.prototype); 

and using foo example,

function foo() {     var bar = false,         ret_obj = new objectwithevents();     settimeout(function () {         bar = true;         ret_obj.dispatchevent({type: 'load'});     }, 1000);     ret_obj.buzz = function () {return bar;};     return ret_obj; }  var fizz = foo();  fizz.addeventlistener('load', function () {     console.log(fizz.buzz()); // logs true }); 

here simplified example of how might implement callback in current code

.factory('gcs', ['$http', function($http) {         var obj= {};          $http.post("mydomina.com?myrequest=getbyid", { "id": "1"} )             .success(function(data) {                obj = data;                code_needing_obj();             })             .error(function(data, status, headers, config) {                 // throw know why code stopped                 return null;             });         return {             all: function() {               return obj;             }         };     }]);  function code_needing_obj() {     // accessing .all here give obj     // etc } 

or re-organise whole code http call before everything

// make sure have $http defined here $http.post("mydomina.com?myrequest=getbyid", { "id": "1"} )     .success(code_needing_obj) // line lets invocation continue     .error(function(data, status, headers, config) {         // throw know why code stopped     });  function code_needing_obj(obj) {     // ...     .factory('gcs', ['$http', function($http) {             return {                 all: function() {                   return obj;                 }             };         }]);     // ...  } 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -