【问题标题】:How to get the returned results from this firebase code如何从此 firebase 代码中获取返回的结果
【发布时间】:2018-02-21 19:42:12
【问题描述】:

下面的代码可以完美地作为 firebase 函数部署(在返回语句中稍作调整),但它在完成时无法返回 JSON 字符串。它在调用时立即返回一个 Promise 对象,我无法从中获得任何结果。

function pCreateBuilding(bn, bl, cFloors, cFlats, wmName, wmMobile, ow)
 {

    var funcSuccess = "";
    var funcResult = "";
    var funcError = "";
    var funcWarning = "";
    var funcFailReason = "";

    var buildingsDb = db.collection('BuildingsDB').doc('BldgProfile').collection('Buildings');

    var newbuilding = {
        Name: bn,
        Location: bl,
        Floors: cFloors,
        Flats: cFlats,
        WMName: wmName,
        WMMobile: wmMobile
    };

    // check if a document exists for the mentioned client name...
    var getBuildingDoc = buildingsDb.doc(bn).get()
        .then((snapshot) => {
            if (snapshot.exists) {

                // The client document exists...
                if (ow.toUpperCase() == 'Y') {
                    // Yes, overwrite existsing client document...
                    return buildingsDb.doc(bn).set(newbuilding);
                }
                else {
                    // Do not overwrite... Return the results...
                    funcSuccess = 'No';
                    funcResult = '{}';
                    funcFailReason = 'Building already exists. No Overwrite.';

                    var funcReturn = {
                        Success: funcSuccess,
                        Result: funcResult,
                        FailReason: funcFailReason,
                        Error: funcError,
                        Warning: funcWarning
                    };
                    console.log(JSON.stringify(funcReturn));
                    return JSON.stringify(funcReturn);
                }
            }
            else {
                // No document exists for this client... Create a new document...
                return buildingsDb.doc(bn).set(newbuilding).then((result) => {
                    // Update Buildings Profile and increment the number of clients by 1...
                    var bldgProfileDb = db.collection('BuildingsDB').doc('bldgProfile').get().then((snapshot) => {
                        var bCount = 0;
                        if (snapshot.exists) {
                            // There are fields in the Assets Profile... Get the ClientsCount value;
                            bCount = snapshot.data().BldgCount;

                        }
                        ++bCount;
                        return db.collection('BuildingsDB').doc('BldgProfile').update({ BldgCount: bCount });
                    });
                });
            }
        })
        .then((result) => {
            // On successful writing of client document to database...
            funcSuccess = 'Ok';
            funcResult = '{}';

            var funcReturn = {
                Success: funcSuccess,
                Result: funcResult,
                FailReason: funcFailReason,
                Error: funcError,
                Warning: funcWarning
            };

            console.log(JSON.stringify(funcReturn));
            return JSON.stringify(funcReturn);

        })
        .catch((err) => {
            funcSuccess = 'No';
            funcResult = '{}';
            funcFailReason = 'Error';
            funcError = err.message;

            var funcReturn = {
                Success: funcSuccess,
                Result: funcResult,
                FailReason: funcFailReason,
                Error: funcError,
                Warning: funcWarning
            };

            console.log(JSON.stringify(funcReturn));
            return JSON.stringify(funcReturn);
        });
}

它用于向firestore数据库添加一条记录,它根据需要执行,但我也想返回处理结果JSON字符串。我哪里做错了?

请帮忙。 谢谢,

【问题讨论】:

  • ok... 那么关于 pCreateBuilding().then(result => { /*whatever*/ } 如何获取我返回的 JSON?
  • 是的......这是一个异步函数,那么如何让浏览器等待它执行并返回?
  • 所以你的意思是说我应该使用类似的东西:var v = pCreateBuilding("B3", "Somewhere", 20, 60, "Xyz", 99632211, "Y").then((result) => { return result; });
  • .then() 代码返回一个错误,指出它不是函数!
  • 在我var v = pCreateBuilding("B3", "Somewhere", 20, 60, "Xyz", 99632211, "Y"); 时返回buildingsDb.doc(bn).get() 返回一个promise 对象那么如何获取从promise 对象返回的JSON?

标签: javascript firebase firebase-realtime-database promise


【解决方案1】:

我在上面的函数中使用了 async / await 如下:

async function pCreateBuilding(bn, bl, cFloors, cFlats, wmName, wmMobile, ow) {
            var funcSuccess = "";
            var funcResult = "";
            var funcError = "";
            var funcWarning = "";
            var funcFailReason = "";
            var res = "";
            var buildingsDb = db.collection('BuildingsDB').doc('BldgProfile').collection('Buildings');

            var newbuilding = {
                Name: bn,
                Location: bl,
                Floors: cFloors,
                Flats: cFlats,
                WMName: wmName,
                WMMobile: wmMobile
            };

            // check if a document exists for the mentioned client name...
            let getBuildingDoc = await buildingsDb.doc(bn).get()
                .then((snapshot) => {
                    if (snapshot.exists) {

                        // The client document exists...
                        if (ow.toUpperCase() == 'Y') {
                            // Yes, overwrite existsing client document...
                            return buildingsDb.doc(bn).set(newbuilding);
                        }
                        else {
                            // Do not overwrite... Return the results...
                            funcSuccess = 'No';
                            funcResult = '{}';
                            funcFailReason = 'Building already exists. No Overwrite.';

                            var funcReturn = {
                                Success: funcSuccess,
                                Result: funcResult,
                                FailReason: funcFailReason,
                                Error: funcError,
                                Warning: funcWarning
                            };
                            // console.log(JSON.stringify(funcReturn));
                            res = JSON.stringify(funcReturn);
                        }
                    }
                    else {
                        // No document exists for this client... Create a new document...
                        return buildingsDb.doc(bn).set(newbuilding).then((result) => {
                            // Update Buildings Profile and increment the number of clients by 1...
                            var bldgProfileDb = db.collection('BuildingsDB').doc('bldgProfile').get().then((snapshot) => {
                                var bCount = 0;
                                if (snapshot.exists) {
                                    // There are fields in the Assets Profile... Get the ClientsCount value;
                                    bCount = snapshot.data().BldgCount;

                                }
                                ++bCount;
                                return db.collection('BuildingsDB').doc('BldgProfile').update({ BldgCount: bCount });
                            });
                        });
                    }
                })
                .then((result) => {
                    // On successful writing of client document to database...
                    funcSuccess = 'Ok';
                    funcResult = '{}';

                    var funcReturn = {
                        Success: funcSuccess,
                        Result: funcResult,
                        FailReason: funcFailReason,
                        Error: funcError,
                        Warning: funcWarning
                    };

                    // console.log(JSON.stringify(funcReturn));
                    res = JSON.stringify(funcReturn);

                })
                .catch((err) => {
                    funcSuccess = 'No';
                    funcResult = '{}';
                    funcFailReason = 'Error';
                    funcError = err.message;

                    var funcReturn = {
                        Success: funcSuccess,
                        Result: funcResult,
                        FailReason: funcFailReason,
                        Error: funcError,
                        Warning: funcWarning
                    };

                    // console.log(JSON.stringify(funcReturn));
                    res = JSON.stringify(funcReturn);
                });
            // console.log(res);
            return res;
        }

然后,我叫它如下:

pCreateBuilding("DB1", "Al Khuwair", 5, 20, "Annand", 99123456, "Y").then(alert); 

这为我提供了传入异步函数的结果,我现在可以根据需要使用它... :)

谢谢大家,希望对大家有用..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 2016-02-12
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    相关资源
    最近更新 更多