【问题标题】:Batch commit been called before batch finishes在批处理完成之前调用批处理提交
【发布时间】:2021-02-27 02:57:30
【问题描述】:

我收到“无法修改已提交的 WriteBatch”。在这个sn-p的代码中。虽然,我很确定为什么 batch.commit() 不等待 forEach 完成。

const db = admin.firestore();
const batch = db.batch();

const channelIds = [];

const messages = data
    .map((item) => {
        if (!item || !item.phone_number)
            return null;

        const msg = pupa(message, item);

        if (!channelIds.includes(item.channel.id))
            channelIds.push(item.channel.id);

        return {
            ...item,
            message: msg
        };
    })
    .filter((msg) => msg);

logger.info(`Creating messages/${messageId}/sms entries. [Count = ${messages.length}]`);

// From all channels included in the messages array, it fetchs its remaining sms credits.
channelIds.forEach(async (channelId) => {
    const subscriptionDetails = (await admin.firestore()
        .collection('channels')
        .doc(channelId)
        .collection('subscription')
        .doc('details')
        .get()).data();

    const creditsRemaining = subscriptionDetails.limits.snapshot.sms_notifications - subscriptionDetails.limits.used.sms_notifications;

    // Sends messages according to its respective channel ID and channel remaining credits.
    messages
        .filter((item) => item.channel.id === channelId)
        .slice(0, creditsRemaining)
        .forEach((msg) => {
            batch.set(db.collection('messages')
                .doc(messageId)
                .collection('sms')
                .doc(), {
                phone_number: msg.phone_number,
                message: msg.message
            });
        });
});

await batch.commit();

编辑:我通过将 forEach 包装在 Promise 中来解决此问题。谢谢!

【问题讨论】:

    标签: node.js firebase google-cloud-firestore async-await google-cloud-functions


    【解决方案1】:

    您似乎在batch.set(db.collection('messages')... 之前缺少一个await,这意味着您的await batch.commit() 在所有batch.set() 调用完成之前运行。

    【讨论】:

    • 我通过将forEach 包装在 Promise 中解决了这个问题。无论如何,谢谢!
    • 很高兴听到@RenatoGuimaraesNunes ? 您可能希望将其发布(使用更新的代码)作为自我回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多