首页 > 解决方案 > 在批处理完成之前调用批处理提交

问题描述

我收到“无法修改已提交的 WriteBatch”。在这段代码中。虽然,我确定为什么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.jsfirebasegoogle-cloud-firestoreasync-awaitgoogle-cloud-functions

解决方案


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


推荐阅读