两个forEach
完成后,我想调用一个回调。我想知道它们何时都完成了对asynchronously
的处理并调用callback
。 console.log("Done")
似乎在两个forEach
const getDates = () => {
const ref = db.ref("reminders");
const dateTime = new Date();
const currentDate = dateFormat(dateTime, "yyyy-mm-dd");
ref
.orderByChild('date')
.endAt(currentDate)
.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}`);
});
}
});
});
}).catch( (error) => {
console.log(error);
});
console.log("Done")
};
输出
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
答案 0 :(得分:1)
从文档中
once(eventType: EventType, successCallback?: function, failureCallbackOrContext?: Object | null, context?: Object | null): Promise<DataSnapshot>
once
返回一个Promise
,这意味着它是异步的,因此console.log("Done")
将在您的forEach()
之前打印。您不知道异步操作何时完成。
因此,解决此问题的最佳方法是在console.log("Done")
内添加forEach()
:
.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");
});
}
});
});
答案 1 :(得分:0)
我不是真的使用firebase,但是如果您要等待多个异步操作,可以使用Promise.all
您只需要将所有异步操作推入数组中。完成后,只需编写如下内容:
Promise.all(yourArrayOfPromise)
.then(() => {
console.log('success');
})
.catch(err => {
console.log(err);
})