Cloud Functions for Firebase: serializing Promises

非 Y 不嫁゛ 提交于 2019-12-22 03:58:53

问题


In an onWrite handler, I'd like to perform multiple reads, manipulate some data, and then store it. I'm fairly new to the Promise concept. Am I safe with the following Promise handling, in regards to Firebase not killing my queries before they're done?

exports.test = functions.database.ref('/zzz/{uid}').onWrite(event => {
    console.log('zzz', event.data.val());

    return Promise.all([
        admin.database().ref('/zzz/1').once('value'),
        admin.database().ref('/zzz/2').once('value')
    ]).then(function(snaps) {
        console.log('loaded', snaps[0].val());
        var updKeys = {
            ["/xxx/" +event.params.uid +"/zoo"]: 'giraffe',
        }

        admin.database().ref().update(updKeys, function(error) {
            console.log("Updating data finished. ", error || "Success.");
        })
    });

});

The above works, but not sure its the right way...


回答1:


If your Function continues to execute after it has returned (or the promise that your function returns has resolved), Google Cloud Functions may interrupt your code at any time. There is however no guarantee that it will do so immediately.

In your code sample, you return the result of the final then(). Since you don't return anything from within that then() block, GCF may interrupt the call to update() or it may continue to let the code run longer than is needed.

To correct this, make sure to "bubble up" the promise from the update() call:

exports.test = functions.database.ref('/zzz/{uid}').onWrite(event => {
    console.log('zzz', event.data.val());

    return Promise.all([
        admin.database().ref('/zzz/1').once('value'),
        admin.database().ref('/zzz/2').once('value')
    ]).then(function(snaps) {
        console.log('loaded', snaps[0].val());
        var updKeys = {
            ["/xxx/" +event.params.uid +"/zoo"]: 'giraffe',
        }

        return admin.database().ref().update(updKeys, function(error) {
            console.log("Updating data finished. ", error || "Success.");
        })
    });

});

In this code, the promise returned by update() is the one being returned to GCF, which gives it the information to leave your function running for precisely as long as it needs.



来源:https://stackoverflow.com/questions/42875400/cloud-functions-for-firebase-serializing-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!