0

I try to call firebase as function from other file to have readable code. But my function return "undefined"

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

Where did go wrong ? What is the best way to export my functions ?

Vivien B
  • 83
  • 8

1 Answers1

0

You need return a Promise, just modified your code like below:

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);
Hung Nguyen
  • 1,026
  • 11
  • 18