【发布时间】: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