Javascript 我的谷歌云功能有承诺问题吗

Javascript 我的谷歌云功能有承诺问题吗,javascript,firebase,google-cloud-firestore,google-cloud-functions,Javascript,Firebase,Google Cloud Firestore,Google Cloud Functions,我在云函数中有一个http触发器正在工作,但是我得到一些日志以奇怪的顺序返回。我很确定我没有正确地履行承诺 代码如下: exports.createGame = functions.https.onRequest((req, res) => { return cors(req, res, () => { // Check for POST request if (req.method !== "POST") { res

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

代码如下:

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()
                }
            })
        }
    })

})
下面是控制台日志的屏幕截图

注意日志的顺序。似乎合乎逻辑的是,在循环的末尾会出现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()
                }
            })
        }

当你重复承诺时,有一件事要记住,如果你做了一件事,它不会等待

看起来OP想要做的是在他点击完成之前,并且做一个res发送,想要确保所有的承诺都已经完成

Promise.all(promises).then(() => {
  res.send({ status: 200, message: 'Game: added.', pin: newGID})
  console.log('completed');
});
答应我,这就是我们要做的

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

所以如果我们更换

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

您的承诺现在已存储,以便以后使用。所有人都可以检查以确保所有内容都已完成。你可以在一行中完成这项工作,但我觉得这样更容易看到发生了什么。eg->

promises.push(promGet.then(snapshot => {
现在我们终于得到了promise数组,在执行res.send之前,让我们确保它们都已完成

Promise.all(promises).then(() => {
  res.send({ status: 200, message: 'Game: added.', pin: newGID})
  console.log('completed');
});
当以这种方式使用承诺时,需要记住的一点是,您同时有相当多的事情在进行,有时这可能是一个问题,例如,连接到某些服务可能会限制并发连接的数量等。因此,在这些情况下,可能是一种串联或两者混合的想法。甚至有LIB可以做concurrecy,例如一次只做X个数量的承诺


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

forEach不会等到您的所有异步内容都完成后才使用它。

;看起来你在这里几乎走对了方向。在你内心深处,把承诺推到这个上面,然后承诺。所有的承诺。then@Keith感谢您的回复,我有两个foreach循环,我应该用哪一个来做呢?@Keith我从这个循环snapshot.forEachfunction doc{还是这个collections.forEachfunction元素中推送{?这完全取决于什么是同步的,什么是异步的,因此查看您的代码元素ref.get是异步的,因此只需将其推到promise数组上。我这样做了。让elementsRef=admin.firestore.collectionelement elementsRef=elementsRef.where'gid','==',targetGID//elementsRef.get.thensapshot=>{const promGet=elementsRef.get;//让我们得到承诺promises.pushpromGet;//放入数组promGet.thensapshot=>{//我们现在可以像以前一样继续,然后这个承诺.allpromises.then=>{res.send{状态:200,消息:“Game:added.”,pin:newGID}console.log'completed';};但它不起作用。不确定我是否这样做了。如果更容易看到,我可以根据您的回答用修改后的代码更新我的问题谢谢您Keith,经过一些重新安排后,我能够使它起作用,如第二次更新中所示。