【问题标题】:Function working well but return undefined函数运行良好但返回未定义
【发布时间】:2019-06-06 22:36:17
【问题描述】:

我尝试从其他文件调用 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

哪里出错了?导出函数的最佳方式是什么?

【问题讨论】:

标签: node.js


【解决方案1】:

您需要返回一个 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 2020-03-19
    • 2023-03-10
    • 1970-01-01
    • 2021-09-14
    • 2019-10-12
    相关资源
    最近更新 更多