Firestore Cloud Function-.then()中无法识别的外部变量的值 [英] Firestore Cloud Function - Value of external variable not recognized in .then()

查看:69
本文介绍了Firestore Cloud Function-.then()中无法识别的外部变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Firestore云函数的新手,并试图运行一个简单的函数来触发一个集合中的onWrite(),并以此为基础,更新另一个集合中的值.

I am new to Firestore cloud functions, and trying to run a simple function that triggers onWrite() in one collection and based on that, updates value in different one.

我遇到了障碍,在... get().then(snapshot)=> {}方法中无法识别变量(实际上是常量数组)的值.据我了解,外部变量的范围也应该在内部,不是吗?我在做什么错了?

I am hitting roadblock where value of variable (const array actually), is not recognized inside the ...get().then(snapshot) => {} method. As I understand the outer variable's scope should be inside as well, shouldn't it? What am I doing wrong?

对该主题的研究使我想到了Promises的概念,我尝试根据get()创建promise值并返回它们,但也无法使用.也许我不正确地使用了它们,如果可以的话,请分享.谢谢.

Research on this topic led me to concept of Promises, and I tried creating promise values based on the get() and returning them, but couldn't work it either. Perhaps I used them incorrectly, if that's the answer please share. Thank you.

更新:我通过将array的值存储在.then()函数外部的变量中进行测试,然后再次尝试,它可以正常工作.似乎正在发生的问题是const myArray [].

UPDATE: I tested by storing the value of array in a variable outside the .then() function, and tried again, and it works correctly. The issue it seems to be happening is with the const myArray[] .

我的下面的代码:

exports.mytestExport = functions.firestore
    .document('col/{docid}')
    .onWrite( (change, context) => {

        const docID = context.params.docid;
        const myArray = change.after.data().someArray;

        const db = admin.firestore();
        const newColRef = db.collection("newCollection");

        for(index = 0; index < myArray.length; index++) {
            console.log(myArray[index]);      //Value Prints here as expected.
            var myArrayValue = myArray[index];
            console.log(typeof(myArray[index])); // Output is 'string'

            let snapshot = newColRef.doc(myArray[index]).get()
                        .then((snapshot) => {

                            console.log(myArray[index]);  // This prints **'undefined'** for all the times 'for' loop is executed.
                            console.log(myArrayValue); // This prints Correctly!

                        if(snapshot.exists) {
                                //my code to update 'newCollection'
                            }
                        })
        }
        return 'success';
    })

非常感谢您的帮助!谢谢,

Your help is much appreciated! Thanks,

推荐答案

@Doug Stevenson答复说,其原因确实是没有正确使用Promises.

As responded by @Doug Stevenson, the cause of this is indeed not using Promises correctly.

对于以后遇到类似问题的任何人,请在下面发布我的认识:

For anyone who has similar issue in future, posting my realization below:

因为无法保证代码在进入下一步for循环之前应该等待

Because there are no promises that the code should wait for before moving to next step, the for loop

for(index = 0; index < myArray.length; index++) {

完全运行,并且index的值为myArray.length(条件失败时).

runs entirely and the value of index is at myArray.length (when the condition fails).

同时get()命令仍在运行,并且在运行时,index的值超出范围,因此无法在数组中找到值,从而导致未定义".

Meanwhile the get() command is still running, and when it runs, the value of index is out of bounds, and so it's not able to find a value in the array, and thus results in 'undefined'.

我发现不使用Promises的一种简单方法是使用'await'而不是链接我的代码(使用.then ...).例如:

An easy way I found without using Promises was to use 'await' instead of chaining my code (with .then...). For ex.:

let snapshot = await newColRef.doc(myArray[index]).get()
if (snapshot.exists)....{}

一旦我对链接更熟悉(.then..then ... catch ... response()),我将更喜欢使用它.

Once I get more comfortable with chaining (.then..then...catch... response()), I will prefer to use that instead.

这篇关于Firestore Cloud Function-.then()中无法识别的外部变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆