我在 for 循环中进行异步调用时遇到问题。在异步调用完成之前循环将继续。我对这种语言很陌生,并试图掌握回调..等。我已经尝试了自调用函数、 promise 和超时,但仍然无法让流程按预期工作。
我希望在将配置文件对象插入消息数组之前完成对 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);
}
感谢任何帮助或指导。
谢谢, 诺埃尔
最佳答案
所以听起来您实际上想要两件事,一是您希望循环在异步调用完成之后才继续。我很确定有一些奇特的方法可以用 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);
}
关于javascript - 在 For 循环中对异步调用进行排序 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39320940/