Firestore Cloud Function - Value of external variable not recognized in .then()

心已入冬 提交于 2021-02-11 14:19:30

问题


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.

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?

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.

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[] .

My code below:

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,


回答1:


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:

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++) {

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

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'.

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)....{}

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



来源:https://stackoverflow.com/questions/58650290/firestore-cloud-function-value-of-external-variable-not-recognized-in-then

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!