问题描述
我知道这个问题已经被问了好几次了,但是经过一天的搜索,我仍然无法解决这个问题,尽管这就像在各处都可以看到的解决方案一样……
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...
我有一个异步请求到数据库,该数据库返回一个数据数组.对于此数组中的每个对象,我需要向数据库启动另一个异步请求,一旦所有这些异步请求都解决了,我想返回它们.我读到你可以用$ q.all(...)
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(...)
所以这是代码:
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');
});});
从控制台中,我看到$ q.all在每个对象之前已解析.我做错什么了吗?这似乎对每个人都有效...
From the console I see that the $q.all is resolved BEFORE each object. Did I get something wrong? This seems to work for everyone...
非常感谢您的帮助,整夜都在看,现在是凌晨5:30,哈哈..
Your help is highly appreciated, been looking the whole night, it's 5:30am now lol..
欢呼
因此,对于以后再来这里的任何人:这只是promises.push(deferred.PROMISE)位.星期四,我读到了anguar.forEach实际上不是推荐的遍历数组的方法,因为它最初并不是为最终用户使用而构造的.不知道这是否正确,但是如果您不想使用angular.forEach,我想出了另一种方法:
So for anyone who's coming here later: It was just the promises.push(deferred.PROMISE) bit. 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. Don't know if that's correct but I figured out another way if you don't want to use 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();
});
和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
}
};
}])
推荐答案
代替
promises.push(deferred);
尝试一下:
promises.push(deferred.promise);
这篇关于在angular.forEach循环中等待promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!