0
votes

i tried to add a trigger function on my cloud functions.

When a document changed i want to perform some work. I have already the code for the work to do in another file (i separate my work into files, so it's get easier for me), so i have a function that performs work and when it is finished the callback is called.

This is what my index.js look like:

// requires...

// Express, i also use express for simulating an API
const app = express()


// So there is my Listener 

const listenerForChange = functions.firestore
    .document('myPath/documentName')
    .onWrite((change, context) => {

      const document = change.after.exists ? change.after.data() : null;

      if (document != null) {
        const oldDocument = change.before.data();
        const newDocument = change.after.data()

        // Here i call my function that is in the worker-listeners.js
        listenerWorker.performStuff(newDocument, function() {
            return 0
        })
      }
      else {
        console.error("Listener for classic was triggered but doc does not exist")
        return 0
      }

    });

const api = functions.https.onRequest(app)
module.exports = {
  api, 
  listenerForChange
}
...

There is my listenerWorker.js :

module.exports = {
    performStuff: function(data, complete) {
      performStuff(data, complete)
    }
}; 


function performStuff(data, complete) {

 // do stuff here ... 

  complete()

} 

Problem is that i always an error in the Firebase console saying : Function returned undefined, expected Promise or value

Even if i do not do anything inside my worker and calling the callback as soon as i can i get the error.

So i understand the functions needs a response, promise or value. But it's like i'm not in the scope anymore but i do not want to return before the work is finished !

Any help ? thank you guys

1

1 Answers

0
votes

All asynchronous work that you perform should be represented by a promise. If you have a utility object that does async work, it should return a promise so that the caller can decide what to do next with it. Right now you're just using callbacks, and that's going to make things much more difficult than necessary (because you'll have to "promisify" those callbacks).

Just use promises everywhere and it'll be much more clear how your function should work.