Firebase云功能在完成foreach之前完成

时间:2019-10-29 22:12:42

标签: javascript firebase promise google-cloud-functions

我想用一些新变量更新“预订”列表。但是我无法使其工作,因为该函数在更新之前就结束了。我知道问题是因为我进行了异步调用,但无法解决。在这种情况下如何使用Promise?

我使用Promise编辑了代码,但仍然没有更新“预订” 返回{“ data”:null}到我的网站控制台 在Firebase控制台中不会产生任何错误。返回消息“已实现预订”

exports.actualizeReservations = functions.https.onCall((data, response) => {
var promisesUpdateReservations = [];
return admin.database().ref(Constants.RESERVATIONS).once("value")
.then((snapshot) => {
    console.log("RESERVATIONS: " + snapshot)
    snapshot.forEach((reserveSnap) => {
        var reserve = reserveSnap.val();
        if(reserve.reservationId && reserve.restoId) {
            admin.database().ref(`${Constants.RESTAURANTS}/${reserve.restoId}`).once("value")
            .then((restoSnap) => {
                if(restoSnap.exists() && restoSnap.val() !== null) {
                    var resto = restoSnap.val();
                    if(resto.address && !resto.address.fullAddress) {
                        var restoAddress = resto.address ? {
                            street: resto.address.street ? resto.address.street : "",
                            fullAddress: resto.address.fullAddress ? resto.address.fullAddress : "",
                            city: resto.address.city ? resto.address.city : "",
                            country: resto.address.country ? resto.address.country : "",
                            postalCode: resto.address.postalCode ? resto.address.postalCode : "",
                            province: resto.address.province ? resto.address.province : "",
                            l: resto.l ? resto.l : null,
                            g: resto.g ? resto.g : null,
                        } : null;
                        var restoUserIDs = `${reserve.restoId}/${reserve.userId}`;
                        const promiseUpdateReservation = admin.database().ref(`${Constants.RESERVATIONS}/${reserve.reservationId}`).update({
                            restoAddress,
                            restoUserIDs
                        })
                        promisesUpdateReservations.push(promiseUpdateReservation)
                    }
                }
            })
            .catch((err) => {
                console.log("resto not found")
            });
        }
    });
    Promise.all(promisesUpdateReservations)
    .then(() => {
        console.log("reservations actualized");
        return { code: 0, result: "successful", description: "reservations actualized" };
    })
})
.catch((err) => {
    console.log("get restaurants error: " + err);
    return { code: 1, result: "successful", description: "reservations not loaded" };;
});
})

1 个答案:

答案 0 :(得分:1)

此函数将在每次调用时立即完成,并且可能不执行任何工作。这是因为它根本没有从顶级函数回调中返回任何内容。相反,您需要从函数的顶层返回一个承诺,该承诺将与数据解析,以便仅在 all 异步工作完成后才发送给客户端(并且您将开始很多在这里)。正确处理承诺对于使Cloud Functions正常工作至关重要。