【问题标题】:Is transaction.set(...) synchronous?transaction.set(...) 是同步的吗?
【发布时间】:2019-07-06 09:19:35
【问题描述】:

我在我的 angular/firebase 项目中处理数据库事务。我有这个:

const transactionResult = await db.runTransaction(async trans => {
            // Get references:
            const parentGroupRef = db.collection('Groups').doc(parentGroupID);
            const childGroupRef = db.collection('Groups').doc(childGroupID);

            // Get documents:
            const promiseArray: Promise<any>[] = [];
            promiseArray.push(trans.get(parentGroupRef));
            promiseArray.push(trans.get(childGroupRef));
            const promiseResults: any[] = await Promise.all(promiseArray);

            // Get the group documents of the promise results:
            const parentGroupDoc = promiseResults.filter(groupDoc => { return groupDoc.id === parentGroupID; })[0];
            const childGroupDoc = promiseResults.filter(groupDoc => { return groupDoc.id === childGroupID; })[0];

            // Get data:
            if (parentGroupDoc && parentGroupDoc.exists && childGroupDoc && childGroupDoc.exists) {
                const parentGroupData = parentGroupDoc.data();
                const childGroupData = childGroupDoc.data();

                // Add child to parent and visa-versa:
                const results: any[] = [];
                if (parentGroupData.childGroupIDs.indexOf(childGroupID) === -1) {
                    parentGroupData.childGroupIDs.push(childGroupID);   
                    const addChildResult = trans.set(parentGroupRef, parentGroupData, {merge: true});
                    results.push(addChildResult);
                }

                if (childGroupData.parentGroupIDs.indexOf(parentGroupID) === -1) {
                    childGroupData.parentGroupIDs.push(parentGroupID);
                    const addParentResult = trans.set(childGroupRef, childGroupData, {merge: true});
                    results.push(addParentResult);
                }

                if (results.length > 0) {
                    return await Promise.all(results);
                } else {
                    return Promise.reject('No changes made');
                }
            } else {
                console.log('Could not find parent or child group, or both.');
                return Promise.reject('Could not find parent or child group, or both.');
            }
        });

如您所见,我正在等待从 trans.get(...) 返回的承诺。对 trans.set(...) 做同样的事情有意义吗?对 trans.get(...) 这样做是有意义的,因为 trans.get(...) 返回一个承诺。但是 trans.set(...) 返回一个事务对象。所以我的问题是:trans.set(...) 是同步的吗?

【问题讨论】:

  • 你有什么问题?既然您自己回答了:如果它不返回 `Promise`,则根据定义它是同步的。

标签: angular firebase promise transactions async-await


【解决方案1】:

与远程服务交互的所有 Firebase API 都是异步的,包括用于事务的 API。

阅读:Why are Firebase APIs Asynchronous?

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 1970-01-01
    • 2017-02-10
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-01-22
    • 2011-10-29
    • 2019-06-04
    相关资源
    最近更新 更多