如何将查询值分配给全局变量?

问题描述 投票:0回答:1

该代码是用来记录某社团的总人数。

import * as functions from 'firebase-functions';

const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();
export const new_reg = functions.firestore
    .document('mobile/{mobile}')
    .onCreate((change, context) =>{
        const society:String = change.get("society")
        let value = 1
        admin.firestore().doc(`society/${society}`).get()
        .then((userSnapshot: { data: () => { (): any; new(): any; users: number; }; }) => {
            value = userSnapshot.data().users
            console.log(value)
        })
        .catch((error: any) => {
            console.log(error)    
        })
        ++value
        console.log(value)
        return null
    })

value "的值没有随着第16行到第24行的代码更新。

注意:- 第18行只是为了确认代码所取的值。

第18行记录在控制台的值总是正确的。

在第24行被递增的值是我最初声明的值,而不是我从firestore获取的值。

typescript firebase google-cloud-platform google-cloud-firestore google-cloud-functions
1个回答
0
投票

get() 立即返回一个承诺。 所以 thencatch. 它们是异步的,回调会在一段时间后调用查询结果。 您的代码不会等待查询结束--它将在查询结束前继续执行并递增值。

使用Cloud Functions后台触发器,您可以 有义务返回一个承诺,当所有异步工作完成后,该承诺将被解析。. 现在,你正在返回null,这根本行不通。 你应该返回以 get().

return admin.firestore().doc(`society/${society}`).get()
    .then(...)
    .catch(...)

我不明白你为什么要和我一起工作?value但无论如何,你需要正确处理承诺。

© www.soinside.com 2019 - 2024. All rights reserved.