![](/img/trans.png)
[英]Why can't I acces a static function in a static Object from the same Class?
[英]why can't I acces object value in javascript
我正在嘗試獲取和分析數據,但是我不知道如何等待上述所有說明完成。
這是我的代碼:
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
}
}
這是我得到的:
經過一些研究,我發現當時console.log()
稱為result['seen']
的值未設置。 但是我不知道該如何解決。
我應該調用一個函數來等待我的http請求完成還是它們是更好的方法?
$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.