功能能否正确处理承诺?

时间:2019-04-12 05:45:36

标签: node.js promise google-cloud-firestore google-cloud-functions

当前,我正在编写一个云函数,该函数将在某些布尔值变为true时触发。这是功能

exports.reveal = functions.database.ref('/reveals/{postIDthatWasRevealed}/revealed').onUpdate((change, context) => {
const revealedValue = change.after.val()

if (revealedValue === true) {
   var updates = {}
   const postID = context.params.postIDthatWasRevealed
   const currentTime = Date.now()
   const addedTime = currentTime + 86400000 
   return admin.firestore().collection('posters').doc(postID).get().then(snapshot => {
        const value = snapshot.data() 
        const posterID = value.posterID
        const posterName = value.posterName
        const profileImage = value.profileImage
        const postKey = value.key
        return admin.database().ref('/convoID/' + postID).once('value', (snapshot) => {
        if (snapshot.exists()) {
           const convoIDCollection = snapshot.val()
           for (var child in convoIDCollection) {
               const convoID = child

               updates["/conversations/"+convoID+"/information/reciever/Name"] = posterName
               updates["/conversations/"+convoID+"/information/reciever/profileImage"] = profileImage
               updates["/conversations/"+convoID+"/key"] = postKey
               updates["/conversations/"+convoID+"/timeOfDeletion"] = addedTime
           }
        }

           const batch = admin.firestore().batch()
           const postFireStoreRef = admin.firestore().collection('posts').doc(postID)

           batch.update(postFireStoreRef,{"revealedDate": currentTime})
           batch.update(postFireStoreRef,{"timeOfDeletion": addedTime})
           batch.update(postFireStoreRef,{"information": {"posterID":posterID,"posterName":posterName,"profileImage":profileImage} })
           batch.update(postFireStoreRef,{"key":postKey})

           return admin.database().ref('/reveals/' + postID).once('value', (snapshot) => {
            if (snapshot.exists()) {
                const revealTotalValue = snapshot.val()
                const revealTotal = revealTotalValue.reveals
                return admin.database().ref('/allTimeReveals/' + posterID).once('value', (snapshot) => {
                    if (snapshot.exists()) {
                        const currentReveals = snapshot.val()
                        const newReveals = currentReveals + revealTotal
                        updates["/allTimeReveals/" + posterID] = newReveals
                    }
                    else {
                        updates["/allTimeReveals/" + posterID] = revealTotal
                    }
                })
            }
           return Promise.all[admin.database().ref().update(updates), batch.commit()]
        })
    })
   })
}
else {
    return null
}
})

但是,当我在单个函数中添加越来越多的数据库查询时,我担心我是否异步触发每个请求...此函数的顺序是否正确?我仍在学习云功能的基础知识,并担心我没有正确处理返回/诺言。

0 个答案:

没有答案
相关问题