Learn JavaScript Promises (Pt. 2) with a Firestore Trigger in Cloud Functions - Firecasts

Firebase · 98K views · 2018 · 6:19

Open on YouTube

Web developmentPython, Ruby & scripting languagestutorial

Why Stack Overflow recommends it

Stack Overflow users link it when explaining that background Cloud Functions must return a promise (or a value) so the runtime knows when the work is finished.

Recommended by 5 people across 12 different months, 2018 to 2024.

What it is

A 6-minute Firecasts episode from the Firebase channel showing how to correctly terminate a background Cloud Function by returning a promise, demonstrated with a Firestore onCreate trigger. It is part two of a short series on JavaScript promises in Cloud Functions.

What people said

Strong rec Renaud Tarnec · 2018-04 · Stack Overflow · on “Firebase Document for each user?”

@NeeronBhatta Also, I would suggest that you have a look at these three videos from the Firebase team: [LINK] & [this video] & [LINK] A must for anyone starting coding for Cloud Functions. Good luck :-) !

Strong rec Renaud Tarnec · 2018-06 · Stack Overflow · on “Request not returning Write to database. Just shows the console”

request supports callback interfaces natively but does not return a promise, which is what you must do within a Cloud Function. I strongly suggest that you watch these videos from the Firebase team: [LINK] and [this video] which explain this key concept. You could use request-promise ( [LINK] ) and rp(...) method which "returns a regular Promises/A+ compliant promise" and then do something like: .... return rp(options) // <- You should return this promise within the Function .then(function (body) { const tokenName = body.notification_key; console.log('Key: ' + tokenName); return db.collection('Users').doc(user_id).set({name: name1,token_id: token_id1,notification_key: tokenName,image: image,email

Strong rec Renaud Tarnec · 2018-07 · Stack Overflow · on “Firebase Firestore update query doesn't execute because of the promise chaining. What am I doing wrong?”

I see two problems in your code: 1/ By doing return fStor.collection('users').get(); you are returning a QuerySnapshot [LINK] and not a DocumentSnapshot . See the doc of the get() method here [LINK] . The doc says that "A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach method. " Therefore when, in then next then(), you do doc.data() you most probably get an error. 2/ The second problem, IMHO, is that you don't return anything in your charge function. Since, in a Cloud Function, you shall return a promise (or a value in specific cases) you should pr

Strong rec Renaud Tarnec · 2018-08 · Stack Overflow · on “Firebase cloud function shows error "No 'Access-Control-Allow-Origin' header is present on the requested resource."”

You should chain your promises, as follows: `var setAda = docRef.set({...}).then(() => {res.status(200).send(setAda);}).catch(err => {res.status(500).send(err);})`. I would suggest that you watch the two following "must see" videos from the Firebase team, about Cloud Functions and promises: [LINK] and [this video]

Strong rec Renaud Tarnec · 2019-06 · Stack Overflow · on “How can I implement a firebase set request within a call back”

In a Cloud Function you should use promises to handle asynchronous tasks (like the HTTP call to the stripe API, or the write to the Realtime Database). By default request does not return promises, so you need to use an interface wrapper for request, like request-promise [LINK] , and adapt your code along the following lines: const rp = require('request-promise'); exports.registerRestaurantPayout = functions.firestore.document('*********') .onCreate((paymentSnap, context) => { var authCode = paymentSnap.data().auth_code; var firstString = 'client_secret=**********='; var secondString = '&grant_type=authorization_code'; var dataString = firstString + authCode + secondString; var options = { me

Recommends Renaud Tarnec · 2018-04 · Stack Overflow · on “Firebase trigger functions works alternately”

The reason is that you have to chain the Promises (and therefore return a promise at each chaining step). The following should work: export const updateTotalAnswersCounts = functions.database .ref('/CurrentGame/answers/{aid}').onWrite((change, context) => { const collectionRef = change.after.ref.parent; let total = 0; return collectionRef.once('value', (snapshot) => { console.log('snapshot', snapshot.val()) snapshot.forEach((childSnapshot) => { if (childSnapshot.val() != null) { console.log('childSnapshot', childSnapshot.val()) total += Number(childSnapshot.val()) } }) }).then(() => { const updates = {} updates['/totalAnswersCount'] = total return firebase.ref('/CurrentGame').update(updates)

Recommends Renaud Tarnec · 2018-05 · Stack Overflow · on “How to clone a node to another path based on a reference value from the initial path on Google Cloud Functions?”

The following should work. const admin = require("firebase-admin"); .... .... exports.updateRoom = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => { const afterData = change.after.val(); // data after the write const roomPushKey = afterData.inRoom; const ins = afterData.ins; const updates = {}; updates['/rooms/' + roomPushKey] = ins; return admin.database().ref().update(updates); }).catch(error => { console.log(error); //+ other rerror treatment if necessary }); Here are some explanations: You get the roomPushKey by reading the "data after the write" as an object: roomPushKey = afterData.inRoom . You don't need to do roomPushKey.once('child_added').then() Once you

Recommends Renaud Tarnec · 2018-05 · Stack Overflow · on “Add same child object in different parents firebase”

Ok. Then Cloud Functions is indeed the way to go. If you are starting with them I would suggest that you have a look at the three following videos from the Firebase team: [LINK] & [this video] & [LINK] And in addition there are some samples from Firebase the team here: [LINK]

Recommends Renaud Tarnec · 2018-06 · Stack Overflow · on “not able to write in firebase realtime database”

The following code should work. Within a Cloud Function triggered by a background event you must return a promise (or in certain cases a value, e.g. return false; ). In addition, since you are writing several times in the database with forEach() , you cannot use the set() method several times at the same reference because you will overwrite each previous write. You should use the update() method (doc is here [LINK] ). exports.sendBigQueryData = functions.analytics.event('buy_from_shop').onLog((event) => { const bigQuery = bigquery({ projectId: }); return bigQuery.query({ // <- here add a return query: 'select email from table', useLegacySql: false }).then(function (results) { console.log(res

Recommends Renaud Tarnec · 2018-06 · Stack Overflow · on “Firebase cloud function error: Function returned undefined, expected Promise or value”

Cloud Functions for Firebase triggered by events in the background must return a promise (or in certain cases a value, e.g. return false; ). Since admin.messaging().send() returns a promise (see doc [LINK] ), you just have to return this promise, as follows: var androidNode = {}; androidNode[constants.propertyNotificationString] = notificationNode; message[constants.propertyAndroidString] = androidNode; .... return admin.messaging().send(message); }) .catch((error) => { console.log('Error sending message:', error); return false; }); However, you are also calling snapshotNotificationMessage.ref.remove(); , which also returns a promise. Therefore you should chain these promises in your Cloud F