Javascript 如何知道异步forEach何时完成
我想在两个forEach都完成后调用回调。我想知道它们何时都完成异步处理并调用回调。console.logDone似乎在两个forEach之前完成 输出Javascript 如何知道异步forEach何时完成,javascript,node.js,firebase,firebase-realtime-database,Javascript,Node.js,Firebase,Firebase Realtime Database,我想在两个forEach都完成后调用回调。我想知道它们何时都完成异步处理并调用回调。console.logDone似乎在两个forEach之前完成 输出 Done AB000001_AB0977 { subtitle: 'Time to start thinking about making a payment', title: 'School Semester 1, 2019 School Fees', userId: 'kXnfHPyxfpeLQ1aCjvl8Pu09sssslou
Done
AB000001_AB0977 { subtitle: 'Time to start thinking about making a payment',
title: 'School Semester 1, 2019 School Fees',
userId: 'kXnfHPyxfpeLQ1aCjvl8Pu09sssslou1' } d-ktpdo45SQ:APA91bF5rJtaHvtNUE42GDssssXoOAP_r7omRmsIs44WKnABsMC8lintdoDBzUYrZ5lutEKECwuaOOIQtdZkKW5Apt4A0ssssyZwdl_epdI2dYHkhk0h-Yns6jzlMbIltSHasA40YL725sssL9TmyCd
Sent notification reminder at AB000001_AB0977
从文档中:
onceeventType:EventType,successCallback?:函数,failureCallbackOrContext?:对象|空,上下文?:对象|空:承诺
一旦返回一个表示它是异步的承诺,那么console.logDone将在forEach之前打印。您无法知道异步操作何时完成 因此,最好的解决方法是在forEach中添加console.logDone:
我并不真正使用firebase,但如果您想等待多个异步操作,可以使用 您只需将所有异步操作推入一个数组中。完成后,只需写下以下内容:
Promise.all(yourArrayOfPromise)
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
})
使用承诺模式代替回调。然后,当所有异步操作完成时,通过编写Promise.all…processNotifications方法的代码是什么?它是异步的吗?是的asynchronous@sk123你试过我的答案了吗?
.once('value', (reminderDates) => {
reminderDates.forEach((singleDate) => {
// iterate over reminder dates
singleDate.forEach( (notificationValues) => {
// iterate over notification codes
if (!notificationValues.key.includes('date')) {
processNotifications(notificationValues, () => {
console.log(`Sent notification reminder at ${notificationValues.key}`);
console.log("Done");
});
}
});
});
Promise.all(yourArrayOfPromise)
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
})