我尝试从其他文件中调用firebase作为函数,以使其具有可读代码。但是我的函数返回“未定义”
const db = require('firebasedbconfiguration');
exports.myFunction = async function(id){
await db.collection('stackovermachin')
.where('condition','==','workingInOtherFile')
.get()
.then(function(snapshot){
if(foo == 'blabla'){
let response = {
bar : bar,
foo : foo
}
console.log(response);
// { bar : bar,
// foo : foo}
return response;
}
.catch((error)=>{
let err = { message : error};
console.log(err)
// message : "error firebase message "
return err;
}
}
------------ (main file) ----------
const import = require('myfile');
let response = await import.myFunction("id99482")
console.log(response);
// undefined
哪里出错了?导出函数的最佳方法是什么?
答案 0 :(得分:0)
您需要返回一个Promise,只需修改您的代码,如下所示:
const db = require('firebasedbconfiguration');
exports.myFunction = async function(id){
try {
let snapshot = await db.collection('stackovermachin')
.where('condition','==','workingInOtherFile')
.get()
if(foo == 'blabla') {
let response = {
bar : bar,
foo : foo
}
return response;
}
} catch (e) {
return { message : e };
}
}
------------ (main file) ----------
const import = require('myfile');
let response = await import.myFunction("id99482")
console.log(response);