我在解决firebase返回的承诺方面遇到了麻烦。这是一个离子 - angularjs - firebase项目,我正在建设中学习。问题是我的函数返回一个包含3个用户数组的promise,但我无法解开这个承诺。
我的代码:
function eventusers(id) {
var userarr = [];
var deferred = $q.defer();
// *The code below makes 2 firebase calls and returns an array of users*
eventref.orderByChild("Eventid").equalTo(eventid).on("value", function(snap) {
var users = snap.val();
angular.forEach(users, function(value,key) {
var obj = value;
for (var prop in obj) {
if(obj[prop] == "True") {
userref.child(prop).on("value", function (snap) {
var id = snap.val().email;
userarr.push(id);
console.log(userarr); // I am able to see the list of users here
});
};
}
});
deferred.resolve(userarr);
});
return deferred.promise;
};
//The console.log shows a promise (pls see the attached pic)
console.log(eventusers(eventid));
// I tried to loop through the response using angular.forEach and also a for loop but it does
//not execute that part of the code as I do not see the response of the console.log. If I
//replace the for loop with just console.log(response), then I get an empty array.
eventusers(eventid).then(function (response) {
for (var i = 0; i <response.length; i++) {
console.log(response[i]);
}
});
答案 0 :(得分:2)
您的延迟承诺在内部异步操作
之前解析userref.child(prop).on('value', ...
完成。
你需要将它包装在另一个延迟对象中,然后返回一个解析所有内部promise的promise。
function eventusers(id) {
return $q(function(resolve) {
eventRef.orderByChild('Eventid').equalTo(id).on('value', function(snap) {
var promises = [];
snap.val().forEach(function(user) {
angular.forEach(user, function(userProp, prop) {
if (userProp === 'True') {
promises.push($q(function(resolve) {
userref.child(prop).on('value', function(snap) {
resolve(snap.val().email);
});
}));
}
});
});
resolve($q.all(promises));
});
});
}
eventusers(eventid).then(function (response) {
for (var i = 0; i < response.length; i++) {
console.log(response[i]);
}
});
答案 1 :(得分:0)
将代码修改为
eventusers(eventid).then(function (response) {
var myArray = response.value;
for (var i = 0; i <myArray.length; i++) {
console.log(myArray[i]);
};
由于您的数组对象位于promise对象
之内<小时/> You can also refer to Plunker