【问题标题】:Firebase Cloud Function Transaction write on firestore throws await as an errorFirebase Cloud Function Transaction 在 Firestore 上写入引发 await 作为错误
【发布时间】:2020-04-13 02:27:48
【问题描述】:

当我尝试在 Firestore 上执行交易时,它会在下面的代码中向我抛出错误 Unexpected token admin

exports.issueBook = functions.https.onCall(async(data, context) => {
    if (!(context.auth && context.auth.token.admin)) {
        throw new functions.https.HttpsError(
            'unauthenticated',
            'only authenticated Admins can Issue Books'
        );
    }

    memberData = {
        name: data.issueData.memberName,
        no: data.issueData.memberNo,
        role: data.issueData.memberRole,
    }
    transactionData = {
        books: data.issueData.books,
        creation: new Date(),
        member: memberData,
    }

    var keys = Object.keys(transactionData.books);
    var date = new Date();
    transactionData.books["takenDate"] = date;
    date.setDate(date.getDate() + 7);
    var dueDate = date;
    if (transactionData.memberRole == "student") {
        transactionData.books["dueDate"] = dueDate;
    }

    const membeRef = admin.firestore().collection('users').doc(transactionData.member.no);
    var memberDoc = await membeRef.get();
    if (!memberDoc.exists) {
        try {
            await memberRef.set({
                name: data.issueData.memberName,
                no: data.issueData.memberNo,
                email: data.issueData.memberEmail,
                role: data.issueData.memberRole,
                created: data.issueData.created,
                totalBooks: 5,
            })
        } catch (error) {
            console.log(error);
            throw new functions.https.HttpsError(
                'unknown',
                'New user cannot be created at the moment due to some unknown reasons. Please try again'
            );
        }
    } else {
        if (memberDoc.data().role == 'student' && keys.length > memberDoc.data().totalBooks) {
            throw new functions.https.HttpsError(
                'failed-precondition',
                'Student cannot have more than 5 Books'
            );
        }
    }

    var transactionBooks = [];

    try {
        keys.forEach(docNo => {
            book = await admin.firestore().collection('books').where("no", "==", docNo).limit(1);
            transactionBooks.push(book);
        })
    } catch (error) {
        console.log(error);
        throw new functions.https.HttpsError(
            'unknown',
            'Book Data cannot be read at the moment. Please try again'
        );
    }

    return admin.firestore().runTransaction(transaction => {
            return transaction.get(memberRef).then(doc => {
                var transactionRef = admin.firestore().collection('transactions').doc();
                var transId = '';
                // write Transaction
                transaction.set(transactionRef, transactionData)
                    .then(() => { transId = transactionRef.id })
                    .catch(error => {
                        console.log(error);
                        throw new functions.https.HttpsError(
                            'unknown',
                            'New user cannot be created at the moment due to some unknown reasons. Please try again'
                        )
                    })

                transaction.set(memberRef, {
                    transactionId: transId
                }, { merge: true })

                transaction.update(membeRef, {
                    totalBooks: totalBooks - keys.length
                });

                transactionBooks.forEach(transBook => {
                    transaction.update(transBook, {
                        status: false
                    })
                })


            })
        })
        .then(result => {
            console.log(result);
            return { message: 'Issued' };
        })
        .catch(error => {
            console.log(error);
            return error;
        });
});

这是我在部署 CF 时遇到的错误

=== Deploying to 'library-1be0e'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint

> functions@ lint /home/abibv/Downloads/Development/PDL Library/Nec-it-Library-PWA/functions
> eslint .


/home/abibv/Downloads/Development/PDL Library/Nec-it-Library-PWA/functions/index.js
  150:26  error  Parsing error: Unexpected token admin

✖ 1 problem (1 error, 0 warnings)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions@ lint: `eslint .`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the functions@ lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/abibv/.npm/_logs/2020-04-13T02_13_51_548Z-debug.log

Error: functions predeploy error: Command terminated with non-zero exit code1

Having trouble? Try firebase [command] --help

这是抛出错误的 try 块

try {
        keys.forEach(docNo => {
            book = await admin.firestore().collection('books').where("no", "==", docNo).limit(1);
            transactionBooks.push(book);
        })
    } catch (error) {
        console.log(error);
        throw new functions.https.HttpsError(
            'unknown',
            'Book Data cannot be read at the moment. Please try again'
        );
    }

这个错误的原因是什么?提前致谢。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore async-await google-cloud-functions


    【解决方案1】:

    您正试图在未声明 async 的函数中使用 await。该函数是您传递给forEach 的匿名函数/lambda。外部函数上的async 在这里根本不重要。 async/await 不适用于嵌套的 lambda 函数。

    考虑一些关于如何在 forEach 循环中使用 async/await 的想法:Using async/await with a forEach loop

    【讨论】:

    • 谢谢。这解决了我的问题。但是现在,我有另一个问题,/home/abibv/Downloads/Development/PDL Library/Nec-it-Library-PWA/functions/index.js 166:21 error Each then() should return a value or throw promise/always-return ✖ 1 problem (1 error, 0 warnings)
    • 如果您有新问题,请将其单独发布并说明现在没有按您预期的方式工作。
    • 在 Stack Overflow 上,如果您发现一个有帮助的答案,习惯上单击答案左侧的复选框来接受它是正确的,因此给出答案的人可以得到认可.
    • 我是这里的新手。感谢您的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2019-01-16
    • 2023-03-13
    • 1970-01-01
    • 2021-03-31
    • 2020-10-19
    相关资源
    最近更新 更多