我在for循环中遇到异步调用问题。循环在异步调用完成之前继续。我对这种语言很陌生并试图掌握回调..等等。我已经尝试过自我调用函数,承诺和超时但仍然无法按预期工作。
我希望在将配置文件对象推入消息数组之前完成对firebase的调用。
python 3.5
感谢任何帮助或指导。
谢谢, 诺尔
答案 0 :(得分:1)
所以听起来你实际上想要两个独立的东西,一个,你希望你的循环在异步调用完成之后才能继续。我很确定有一些奇特的方法可以用es6做这个,但是你没有使用es6。我不确定你为什么要让循环等待呢?所以我通过使用while循环即兴创作。第二,你想要“在将配置文件对象推入消息数组之前完成对firebase的调用。”这是通过将推送调用置于第一个注释中提到的value
事件处理程序中来完成的。
// returns the chats for that profile
Chat.allChatsByUser(uid).$loaded()
.then(function(data) {
var i = 0;
var inProgress = false;
while (i < data.length) {
// self calling function for async callback handling
// this ensures that the async call is run for every iteration in the loop
// wait until last iteration has completed
while(inProgress);
// the function is about to begin
inProgess = true;
(function(i) {
// increment i here
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();
// wait until event
// pushes chatting users profile into the array
chat.messages.push(profile);
// allow next iteration to continue
inProgess = false;
});
} else {
// invalid response
return $q.reject(profile);
}
},
function(profile) {
// promise rejected END script
return console.log('error', error);
});
// i argument as closure
})(i);
}
答案 1 :(得分:1)
在chat.messages.push(profile)
处理程序
value
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);
});
答案 2 :(得分:0)
我认为.all方法是这样的方法。例如:
-renamesourcefileattribute SourceFile
答案 3 :(得分:0)
在值事件处理程序中推送到数组:
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);
});