[英]Javascript Web API call in for loop
I am developing an app with angularjs and ionic. 我正在使用angularjs和ionic开发一个应用程序。 There I have an array with ids.
那里我有一个ID数组。 And from all these ids I need to have a name.
从所有这些ID中,我需要有一个名称。 Now I tried it with the code below:
现在,我尝试使用以下代码:
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;
It is all ok when I debug. 调试时一切正常。 I always get the name back.
我总是把名字取回来。 But in $scope.resources there is nothing, it is empty, also the array arrayWithNames.
但是在$ scope.resources中什么也没有,它是空的,还有数组arrayWithNames。
Do I miss something? 我想念什么吗? What is the problem?
问题是什么?
Thanks. 谢谢。
The ResourceService.get()
call is asynchronous (and also a Promise), and this line ResourceService.get()
调用是异步的(也是Promise),这一行
$scope.resources = arrayWithNames;
is getting called before the ResourceService.get()
callback. 在
ResourceService.get()
回调之前被调用。
You can drop arrayWithNames
and directly push to $scope.resources
: 您可以删除
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.