plean plean - 26 days ago 6
Javascript Question

why can't I acces object value in javascript

I'm trying to get and analyse data but I don't know how to wait till every above instructions are done.

Here is my code:

function get_unicodes() {
var deferred = $q.defer();

var result = {'seen': [], 'all': []};

var unicode_seen_raw = window.localStorage.getItem('LISTE_CARACTERES').split(" ");
var unicode_all = window.localStorage.getItem('CAROBJECTIF').split(" ");

for (value in unicode_seen_raw) {
$http({
method: 'post',
url: DataService.URL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data: $httpParamSerializerJQLike({ no_requete: 16, sParam: value })
}).then(function (res, data) {
result['seen'].push(JSON.parse(res['data']['data'])[0]);
});
}
for (value in unicode_all) {
$http({
method: 'post',
url: DataService.URL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
data: $httpParamSerializerJQLike({ no_requete: 16, sParam: value })
}).then(function (res, data) {
result['all'].push(JSON.parse(res['data']['data'])[0]);
});
}

console.log(result);
console.log(result['seen']);
deferred.resolve(result);
return deferred.promise;
}

function update_biblio() {
get_unicodes().then(function (res) {
// stuff I want to do with res but can't
}
}


Here is what I get:

enter image description here

after some research I found that at the time
console.log()
is called
result['seen']
's value isn't set. But I don't know how to fix this.

Should I call a function to wait till my http requests are done or they're a better way to do it ?

Answer

$http is asynchronous so you are resolving the promise immediately and before any of the requests have even completed.

You could use $q.all() for this along with an array of promises returned by $http

 function get_unicodes() {
     // array to store all the request promises
     var promises = [];

     var result = {'seen': [],'all': []};

     var unicode_seen_raw = window.localStorage.getItem('LISTE_CARACTERES').split(" ");
     var unicode_all = window.localStorage.getItem('CAROBJECTIF').split(" ");

     for (value in unicode_seen_raw) {
       var req1 = $http(...).then(function(res, data) {
         result['seen'].push(JSON.parse(res['data']['data'])[0]);
       });
       // push this promise to promise array
       promises.push(req1);
     }
     for (value in unicode_all) {
       var req2 = $http(...).then(function(res, data) {
         result['all'].push(JSON.parse(res['data']['data'])[0]);
       });
       // push this promise to promise array
       promises.push(req2);
     }

     // return the `$q.all()` promise
     return $q.all(promises).then(function() {
       // fires after all promises in array are resolved
       console.log(result);
       console.log(result['seen']);
       // return result
       return result;
     }).catch(function() {
         // do something when not all requests succeed
     });
}