[英]Wait for promises inside of a angular.forEach loop
I know this has been asked quite a few times already but after a day of search I still don't get it to work, although it's just like what is shown as a solution everywhere... 我知道这个问题已经被问过好几次了,但是经过一天的搜索,我仍然没有使它起作用,尽管这就像到处都可以看到的解决方案一样。
I have a async request to a database which returns an array of data. 我有一个异步请求到数据库,该数据库返回数据数组。 For each object in this array I need to start another async request to the database and as soon as ALL of these async requests resolve, I want to return them.
对于此数组中的每个对象,我需要向数据库启动另一个异步请求,并且一旦所有这些异步请求都解决了,我想返回它们。 I read you could do it with $q.all(...)
我读到你可以用$ q.all(...)
So here's the code: 所以这是代码:
Factory.firstAsyncRequest(id).then(function (arrayWithObjects) {
var promises = [];
var dataArr = [];
angular.forEach(arrayWithObjects, function (object, key) {
var deferred = $q.defer();
promises.push(deferred);
Factory.otherAsyncRequest(key).then(function (objectData) {
dataArr.push({
name: objectData.name,
key: key,
status: objectData.status
});
deferred.resolve();
console.info('Object ' + key + ' resolved');
});
});
$q.all(promises).then(function () {
$rootScope.data = dataArr;
console.info('All resolved');
});});
From the console I see that the $q.all is resolved BEFORE each object. 从控制台中,我看到$ q.all在每个对象之前已解析。 Did I get something wrong?
我做错了吗? This seems to work for everyone...
这似乎对每个人都有效...
Your help is highly appreciated, been looking the whole night, it's 5:30am now lol.. 非常感谢您的帮助,整夜都在寻找,现在是凌晨5:30,大声笑。
Cheers 干杯
EDIT: So for anyone who's coming here later: It was just the promises.push(deferred.PROMISE) bit. 编辑:所以对于以后再来这里的任何人:这只是promises.push(deferred.PROMISE)位。 Tho, I read that anguar.forEach is actually not a recommended method to loop through array because it was originally not constructed to be used by the end-user.
星期四,我读到了anguar.forEach实际上不是推荐的遍历数组的方法,因为它最初并不是为最终用户使用而构造的。 Don't know if that's correct but I figured out another way if you don't want to use angular.forEach:
不知道这是否正确,但是如果您不想使用angular.forEach,我想出了另一种方法:
Users.getAll(uid).then(function (users) {
var uids = ObjHandler.getKeys(users); //own function just iterating through Object.keys and pushing them to the array
var cntr = 0;
function next() {
if (cntr < uids.length) {
Users.getProfile(uids[cntr]).then(function (profile) {
var Profile = {
name: profile.name,
key: uids[cntr],
status: profile.status
});
dataArr[uids[cntr]] = Profile;
if(cntr===uids.length-1) {
defer.resolve();
console.info('Service: query finished');
} else {cntr++;next}
});
}
}
next();
});
And the getKey function: 和getKey函数:
.factory('ObjHandler', [
function () {
return {
getKeys: function(obj) {
var r = [];
for (var k in obj) {
if (!obj.hasOwnProperty(k))
continue;
r.push(k)
}
return r
}
};
}])
Instead of 代替
promises.push(deferred);
Try this: 尝试这个:
promises.push(deferred.promise);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.