gpt4 book ai didi

javascript - 如何知道异步 forEach 何时完成

转载 作者:行者123 更新时间:2023-12-02 23:54:22 25 4
gpt4 key购买 nike

我想在两个 forEach 完成时调用回调。我想知道它们何时完成异步处理并调用回调。 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

最佳答案

来自文档:

once

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");
});
}
});
});

关于javascript - 如何知道异步 forEach 何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55470106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com