Seeking guidance on handling promises in AngularJS as a newcomer. Struggling with merging data from two asynchronous arrays into a single array within a for-loop. Encountering a bug where the same picture is displayed for all entries despite different user data. The issue seems to lie in the code snippet below:
userPromise.then(function(user){
picPromise.then(function(url){
newfriendsinfo.push({
id: newfriendid,
name: user.val().name,
email: user.val().email,
agreed: newfriendagreed,
profilepicture: url
});
}).then(function(){
if (newfriendsinfo.length == newfriends.length){
deferred.resolve(newfriendsinfo);
}
});
});
The challenge is apparent, but solutions like multiple deferred variables and $q.all haven't provided a clear path forward. Your input is valued, thank you :)
var friendsRef = firebase.database().ref('friendships/' + firebase.auth().currentUser.uid);
$scope.friends = $firebaseArray(friendsRef);
$scope.friendsinfo = [];
$scope.$watch('friends', function() {
var newfriends = $scope.friends;
asyncUpdateFriendsInfo(newfriends).then(function(newlist){
$scope.friendsinfo = newlist;
});
}, true);
function fetchPicture(ref){
return ref.getDownloadURL().then(function(url) {
return url;
}).catch(function(error) {
alert("error");
});
}
function fetchUserInfo(ref){
return ref.once('value', function(snapshot){
}).then(function(snapshot){
return snapshot;
});
}
function asyncUpdateFriendsInfo(newfriends){
var deferred = $q.defer();
var newfriendsinfo = [];
for(var i = 0; i < newfriends.length; i++){
var ref = firebase.database().ref('users/' + newfriends[i].$id);
var profilePicRef = firebase.storage().ref("profilepictures/" + newfriends[i].$id + "/profilepicture");
var userPromise = fetchUserInfo(ref);
var picPromise = fetchPicture(profilePicRef);
var newfriendid = newfriends[i].$id;
var newfriendagreed = newfriends[i].agreed;
userPromise.then(function(user){
picPromise.then(function(url){
newfriendsinfo.push({
id: newfriendid,
name: user.val().name,
email: user.val().email,
agreed: newfriendagreed,
profilepicture: url
});
}).then(function(){
if (newfriendsinfo.length == newfriends.length){
deferred.resolve(newfriendsinfo);
}
});
});
}
return deferred.promise;
}