[英]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.