Experiencing issues with asynchronous calls within a for loop in my code. The loop progresses before the async call is completed, causing unexpected behavior. As someone new to this language, I'm trying to understand callbacks and other related concepts. I've experimented with self-calling functions, promises, and timeouts, but haven't achieved the desired flow.
The goal is to ensure that the firebase call finishes before adding the profile object to the messages array.
// Retrieving chats associated with the user
Chat.allChatsByUser(uid).$loaded()
.then(function(data) {
for (var i = 0; i < data.length; i++) {
// Utilizing a self-calling function to handle async callbacks
// Ensuring the async call is executed during each iteration of the loop
(function(i) {
var item = data[i];
// Fetching profile information for the matched user
Auth.getProfile(item.$id).$loaded()
.then(function(profile) {
// Handling success case
if (typeof profile === 'object') {
if(chat.keyOrder == 'true') {
// Retrieving last chat from firebase
// DESIRE THIS TO COMPLETE BEFORE PROCEEDING
ref.child('chatting').child('messages').child(chat.chatId).on("value", function(data) {
profile.lastChat = data.child('lastMsg').val();
});
// Adding chatting user's profile to the array
chat.messages.push(profile);
} else {
// Invalid response
return $q.reject(profile);
}
}, function(profile) {
// Promise rejected
console.log('error', error);});
})(i);
}
Any help or guidance would be greatly appreciated.
Regards, Noel