1
下面的代码来直Firebase Functions getting started tutorial:为什么数据库快照未定义Firebase管理节点Js?
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.addMessage = functions.https.onRequest((req, res) => {
let userid = 'afewfaewf';
let dummyJson = {key: 'value'};
let dbPath = '/' + userid;
admin.database().ref(dbPath).update({dummy: dummyJson}).then(snapshot => {
console.log('finished writing to Firebase database ');
console.log(snapshot === undefined);
res.redirect(303, snapshot.ref);
});
});
这里是在本地运行它的全部输出:
❯ firebase serve --only functions
=== Serving from '/Users/eric/AndroidStudioProjects/XXX/firebase-functions'...
i functions: Preparing to emulate HTTPS functions. Support for other event types coming soon.
Warning: You're using Node.js v7.7.1 but Google Cloud Functions only supports v6.9.1.
Server#addProtoService is deprecated. Use addService instead
✔ functions: addMessage: http://localhost:5002/xxx/us-central1/addMessage
info: User function triggered, starting execution
info: finished writing to Firebase database
info: true
error: (node:11005) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'ref' of undefined
(node:11005) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
而关于云:
11:44:06.290 PM
warning
addMessage
TypeError: Cannot read property 'ref' of undefined at admin.database.ref.update.then.snapshot (/user_code/index.js:32:31) at process._tickDomainCallback (internal/process/next_tick.js:129:7)
TypeError: Cannot read property 'ref' of undefined
at admin.database.ref.update.then.snapshot (/user_code/index.js:32:31)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
11:44:06.289 PM
warning
addMessage
Unhandled rejection
11:44:06.288 PM
info
addMessage
true
11:44:06.283 PM
info
addMessage
finished writing to Firebase database
11:44:05.322 PM
outlined_flag
addMessage
Function execution started
因为这些代码是错误的。 'update'返回一个解析为'void'(即'undefined')的promise - 而不是'Snapshot'。 – cartant
https://firebase.google.com/docs/reference/node/firebase.database.Reference#update – cartant
谢谢@cartant,你介意把它放在答案中,以便我可以接受它吗?顺便说一句,你能否详细说明如何使用“承诺”,是否需要某种异步回调来获得结果,无论我的更新是否失败或最终成功? – ericn