【问题标题】:how to run firebase query inside a function in node js如何在节点js中的函数内运行firebase查询
【发布时间】:2018-08-21 17:58:52
【问题描述】:
我有一个函数应该查询 firebase db 并返回结果。
function verifyToken(token)
{
var androidId = 'xxxxx';
admin.database(dbDEV).ref('profiles').orderByChild('androidId').equalTo(androidId).on('value',(snapshot)=>{
console.log(snapshot.val());
return snapshot.val();
});
}
我为此使用了 firebase 函数。所以结果是登录到firebase日志中,但在执行函数时我没有得到并返回值。
【问题讨论】:
标签:
firebase
asynchronous
firebase-realtime-database
google-cloud-functions
【解决方案2】:
你可以从使用 Promise 开始。例如:
function verifyToken(token) {
return new Promise(resolve => {
var androidId = 'xxxxx';
admin.database(dbDEV).ref('profiles').orderByChild('androidId').equalTo(androidId).on('value',(snapshot)=>{
console.log(snapshot.val());
resolve(snapshot.val());
});
});
}
当你需要结果时:
verifyToken(token).then(result => {
... do stuff
});
要改进这一点,您可以使用异步函数。例如:
async function foo() {
const result = await verifyToken(token);
console.log(result);
}