【发布时间】:2023-03-29 14:25:01
【问题描述】:
我遇到了 for 循环中的异步调用问题。循环在异步调用完成之前继续。我对这种语言很陌生,并试图掌握回调..等。我尝试了一个自调用函数、promise 和 timeout,但仍然无法让流程按预期工作。
我希望在配置文件对象被推送到消息数组之前完成对 firebase 的调用。
// returns the chats for that profile
Chat.allChatsByUser(uid).$loaded()
.then(function(data) {
for (var i = 0; i < data.length; i++) {
// self calling function for async callback handling
// this ensures that the async call is run for every iteration in the loop
(function(i) {
var item = data[i];
// function to arrange users and chats fom newest to oldest
// for each matched user. item.$id = uid
Auth.getProfile(item.$id).$loaded()
.then(function(profile) {
// first function handles success
if (typeof profile === 'object') {
if(chat.keyOrder == 'true') {
// get last chat from firebase
// WANT THIS COMPLETE BEFORE CONTINUING
ref.child('chatting').child('messages').child(chat.chatId).on("value", function(data) {
profile.lastChat = data.child('lastMsg').val();
});
// pushes chatting users profile into the array
chat.messages.push(profile);
} else {
// invalid response
return $q.reject(profile);
}
}, function(profile) {
// promise rejected
console.log('error', error);});
// i argument as closure
})(i);
}
感谢任何帮助或指导。
谢谢, 诺埃尔
【问题讨论】:
-
您是否尝试过在
value事件处理程序中包含chat.messages.push(profile);? -
正确。那解决了它。感谢您花时间查看和回复 :-) 如此简单,但让我头疼了好几个小时!
标签: javascript angularjs ionic-framework firebase firebase-realtime-database