[英]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: 这是我得到的:
after some research I found that at the time console.log()
is called result['seen']
's value isn't set. 经过一些研究,我发现当时console.log()
称为result['seen']
的值未设置。 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 ? 我应该调用一个函数来等待我的http请求完成还是它们是更好的方法?
$http
is asynchronous so you are resolving the promise immediately and before any of the requests have even completed. $http
是异步的,因此您可以在任何请求甚至尚未完成之前立即兑现承诺。
You could use $q.all()
for this along with an array of promises returned by $http
您可以使用$q.all()
以及$http
返回的promise数组
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
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.