Skip to content Skip to sidebar Skip to footer

Having A Promise Issue With My Google Cloud Function

I have an http trigger in cloud functions that is working, however I am getting some logs come back in a weird order. I am pretty sure I have not executed the promises correctly. h

Solution 1:

When looping with promises, one thing to remember is if you do a forEach, it's not going to wait.

It appears that what the OP wants to do is before he hits the complete, and does a res send, wants to make sure all promises have been completed.

Promise.allhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all , is exactly what this does.

So every time you create a promise if you push this onto an array, we can later use Promise.all to make sure all the promises are complete.

So if we replace

elementsRef.get().then(snapshot => {

with

const promGet = elementsRef.get();  //lets get our promise
promises.push(promGet);             //place into an array
promGet.then(snapshot => {          //we can now continue as before

Your promise is now stored for later so that Promise.all can check to make sure everything has complete. You could do this in one line, but I feel it's easier to see what's happening this way. eg->

promises.push(promGet.then(snapshot => {

Finally now we have got our promise array, before we do our res.send, lets make sure they have all completed.

Promise.all(promises).then(() => {
  res.send({ status: 200, message: 'Game: added.', pin: newGID})
  console.log('completed');
});

One thing to keep in mind when using Promises this way, is that you have a fair few things going on at the same time, sometimes this can be an issue, eg. connected to some service might put restrictions on the number of concurrent connections etc. So in these cases it might be an idea doing things in series or a mix of both. There are even libs that can do concurrecy, eg. Do only X amounts of promises at a time.

And finally, if you can use async / await, I'd advice using them, as it makes Promises so much nicer to work with.

Post a Comment for "Having A Promise Issue With My Google Cloud Function"