javascript - 我的谷歌云功能有 promise 问题

标签 javascript firebase google-cloud-firestore google-cloud-functions

我在云函数中有一个正在运行的http触发器,但是我收到一些日志以奇怪的顺序返回。我很确定我没有正确履行 promise 。

这是代码:

exports.createGame = functions.https.onRequest((req, res) => {
    return cors(req, res, () => {

        // Check for POST request
        if (req.method !== "POST") {
            res.status(400).send('Please send a POST request');
            return;
        }
        const createGame = admin.firestore().collection('games')

        generatePin() 

        function generatePin() {
            ...pin generating code goes here...

            addGame(newGidToString)
        }

        function addGame(newGidToString) {
            var getGame = admin.firestore().collection('games')
            getGame = getGame.where('gid', '==', newGidToString)
            getGame.get().then(snapshot => {
                if (snapshot.empty) {

                    console.log('BODY ', req.body)

                    const promises = [];

                    const gameTitle = req.body.gametitle
                    const targetGID = req.body.target
                    const numPlayers = req.body.playercount.toString()

                    const newGID = newGidToString
                    const collections = ['games', 'clues', 'detours', 'messages', 'questions', 'tagstate']
                    collections.forEach(function (element) {
                        console.log('start loop', element)
                        let elementsRef = admin.firestore().collection(element)
                        elementsRef = elementsRef.where('gid', '==', targetGID)
                        elementsRef.get().then(snapshot => {
                            var batch = admin.firestore().batch()
                            snapshot.forEach(function (doc) {
                                // change the gid to the new game gid
                                let data = doc.data()
                                data.gid = newGID

                                if(data.template){
                                    data.template = false
                                }

                                if(!data.parent) {
                                    data.parent = targetGID
                                }

                                if (!data.playercount) {
                                    data.playercount = numPlayers
                                }

                                if (data.gametitle) {
                                    data.gametitle = gameTitle
                                }

                                let elementRef = admin.firestore().collection(element).doc()
                                batch.set(elementRef, data)
                            })
                            batch.commit().then(data => {
                                console.log('complete batch ', element)
                            })
                        })
                    })
                    res.send({ status: 200, message: 'Game: added.', pin: newGID})
                    console.log('completed');
                } else {
                    console.log('found a match ', snapshot)
                    // re-run the generator for a new pin
                    generatePin()
                }
            })
        }
    })

})

这是控制台日志的屏幕截图。

enter image description here

注意日志的顺序。 completed 出现在循环的末尾似乎是合乎逻辑的。

非常感谢任何帮助。

更新:

function addGame(newGidToString) {
            var getGame = admin.firestore().collection('games')
            getGame = getGame.where('gid', '==', newGidToString)
            getGame.get().then(snapshot => {
                if (snapshot.empty) {

                    console.log('BODY ', req.body)

                    const promises = [];

                    const gameTitle = req.body.gametitle
                    const targetGID = req.body.target
                    const numPlayers = req.body.playercount.toString()

                    const newGID = newGidToString

                    const collections = ['games', 'clues', 'detours', 'messages', 'questions', 'tagstate']
                    collections.forEach(function (element) {

                        console.log('start loop', element)

                        let elementsRef = admin.firestore().collection(element)
                        elementsRef = elementsRef.where('gid', '==', targetGID)
                        // elementsRef.get().then(snapshot => {

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

                            var batch = admin.firestore().batch()

                            snapshot.forEach(function (doc) {
                                // change the gid to the new game gid
                                let data = doc.data()
                                data.gid = newGID

                                if(data.template){
                                    data.template = false
                                }

                                if(!data.parent) {
                                    data.parent = targetGID
                                }

                                if (!data.playercount) {
                                    data.playercount = numPlayers
                                }

                                if (data.gametitle) {
                                    data.gametitle = gameTitle
                                }

                                let elementRef = admin.firestore().collection(element).doc()
                                batch.set(elementRef, data)
                            })
                            batch.commit().then(data => {
                                console.log('complete batch ', element)
                            })

                        })
                    })
                    Promise.all(promises).then(() => {
                        res.send({ status: 200, message: 'Game: added.', pin: newGID })
                        console.log('completed');
                    });
                    // res.send({ status: 200, message: 'Game: added.', pin: newGID})
                    // console.log('completed');
                } else {
                    console.log('found a match ', snapshot)
                    // re-run the generator for a new pin
                    generatePin()
                }
            })
        }

第二次更新:(基于基思的回答)

function addGame(newGidToString) {
            var getGame = admin.firestore().collection('games')
            getGame = getGame.where('gid', '==', newGidToString)
            getGame.get().then(snapshot => {
                if (snapshot.empty) {

                    console.log('BODY ', req.body)

                    const gameTitle = req.body.gametitle
                    const targetGID = req.body.target
                    const numPlayers = req.body.playercount.toString()

                    const newGID = newGidToString

                    const promises = [];

                    const collections = ['games', 'clues', 'detours', 'messages', 'questions', 'tagstate']
                    collections.forEach(function (element) {

                        console.log('start loop', element)

                        let elementsRef = admin.firestore().collection(element)
                        elementsRef = elementsRef.where('gid', '==', targetGID)

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

                            var batch = admin.firestore().batch()

                            snapshot.forEach(function (doc) {
                                // change the gid to the new game gid
                                let data = doc.data()
                                data.gid = newGID

                                if(data.template){
                                    data.template = false
                                }

                                if(!data.parent) {
                                    data.parent = targetGID
                                }

                                if (!data.playercount) {
                                    data.playercount = numPlayers
                                }

                                if (data.gametitle) {
                                    data.gametitle = gameTitle
                                }

                                let elementRef = admin.firestore().collection(element).doc()
                                batch.set(elementRef, data)
                            })
                            batch.commit()
                        })
                    })
                    Promise.all(promises).then(() => {
                        res.send({ status: 200, message: 'Game: added.', pin: newGID })
                        console.log('completed from promise');
                    });
                } else {
                    console.log('found a match ', snapshot)
                    // re-run the generator for a new pin
                    generatePin()
                }
            })
        }

最佳答案

当使用 Promise 循环时,要记住的一件事是,如果您执行 forEach,它不会等待。

看来OP想要做的是在完成之前,并进行重新发送,希望确保所有 promise 都已完成。

Promise.all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all ,这正是它的作用。

因此,每次创建 promise 时,如果将其推送到数组中,我们稍后可以使用 Promise.all 来确保所有 promise 都已完成。

所以如果我们替换

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

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

您的 Promise 现在已存储以供稍后使用,以便 Promise.all 可以检查以确保一切都已完成。您可以在一行中完成此操作,但我觉得这样更容易看到发生了什么。例如->

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

现在我们终于得到了 Promise 数组,在执行 res.send 之前,让我们确保它们都已完成。

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

以这种方式使用 Promise 时要记住的一件事是,您会同时发生很多事情,有时这可能是一个问题,例如。连接到某些服务可能会限制并发连接的数量等。因此,在这些情况下,可能会考虑串行执行操作或两者混合执行操作。甚至还有可以并发的库,例如。一次只执行 X 数量的 Promise。

最后,如果您可以使用async/await,我建议使用它们,因为它使 Promise 更易于使用。

关于javascript - 我的谷歌云功能有 promise 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972558/

相关文章:

javascript - 在 Ajax 结果后多次打印一个 div

javascript - Firestore Cloud Functions 优先级

javascript - 如何解构云函数参数?

javascript - Firebase 检索返回未定义/对象对象

json - 从 BigQuery 中的字符串化 JSON 解析时间戳对象

javascript - Chrome控制台清除赋值和变量

javascript - Chartjs 折线图覆盖面板

javascript - 如何从 for 循环返回解析 Promise Like 对象

swift - 从自动 ID 数据库子项中检索数据

Firebase 云功能中的 Firebase 存储错误