[英]Javascript Web API call in for loop
我正在使用angularjs和ionic開發一個應用程序。 那里我有一個ID數組。 從所有這些ID中,我需要有一個名稱。 現在,我嘗試使用以下代碼:
var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
var arrayWithNames = [];
for (var j = 0; j < arrayWithIds.length; j++) {
ResourceService.get(arrayWithIds[j]).then(function(resource) {
arrayWithNames.push(resource.Name);
},function(error) {
alert(error.message);
});
}
$scope.resources = arrayWithNames;
調試時一切正常。 我總是把名字取回來。 但是在$ scope.resources中什么也沒有,它是空的,還有數組arrayWithNames。
我想念什么嗎? 問題是什么?
謝謝。
ResourceService.get()
調用是異步的(也是Promise),這一行
$scope.resources = arrayWithNames;
在ResourceService.get()
回調之前被調用。
您可以刪除arrayWithNames
並直接推送到$scope.resources
:
var arrayWithIds = [1, 2, 3, 4, 5, 6, 7]
$scope.resources = [];
for (var j = 0; j < arrayWithIds.length; j++) {
ResourceService.get(arrayWithIds[j]).then(function(resource) {
$scope.resources.push(resource.Name);
},function(error) {
alert(error.message);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.