简体   繁体   中英

Firebase nodejs doesn't execute return function properly

We are trying to get timeslots from our database by pushing them into an array and then returning it. The array does get filled properly according to the firebase logs, however the function never returns the data properly at all, even though we see the data to be returned. Basically, the execution does not reach the return statement.

Our goal is to get all of the timeslots in this photo. Is there any neat way to do this? 在此处输入图像描述

exports.getTimeslots = functions.region('europe-west2').https.onCall((data, context) => {
  const uid = context.auth.uid;
  let array = [];
  if (!uid)
    throw new functions.https.HttpsError('no-userid', 'The requested user was not found');
  else
    return admin.firestore().collection('users').doc(uid).collection('modules').where('name', '!=', '').get().then(snapshot => {
      snapshot.forEach(async doc => {
        await admin.firestore().collection('users').doc(uid).collection('modules').doc(doc.id).collection('timeslots').where('length', '!=', -1).get().then(snapshot2 => {
          snapshot2.forEach(doc2 => {
            array.push(Object.assign(doc2.data(), {id: doc2.id, modID: doc.id}))
            console.log("identifier #1", array) 
          })
          console.log("Got outside");
        })
        console.log("Got more outside");
      })
      console.log("Got the most outside")
      return ({ data: array });
    });
  //console.log("I have escaped!")
})

This is a issue with how your function is written. Instead of

  return ({ data: array });

Your function sometimes returns.

  admin.firestore().collection('users').doc(uid).collection('modules').where('name', '!=', '').get()

Which is a promise by itself. You are chaining async inside then function. The solution is to make everything async await.

 const data = await admin.firestore().collection('users').doc(uid).collection('modules').where('name', '!=', '').get()

 

As @Ragesh Ramesh also said: "The solution is to make everything async await.", I tried replicating your code using the data structure, and code below:

Data Structure:

在此处输入图像描述

Code:

// firebase db
const db = firebase.firestore();

exports.getTimeslots = functions.region('europe-west2').https.onCall((data, context) => {  
    const getData = async () => {
        const uid = context.auth.uid;
        let array = [];

        if (!uid) {
            throw new functions.https.HttpsError('no-userid', 'The requested user was not found');
        } else {
            const modulesRef = db.collection('users').doc(uid).collection('modules');
            const modulesQuery = modulesRef.where('name', '!=', '');
            const modulesQuerySnap = await modulesQuery.get();
            const moduleDocuments = modulesQuerySnap.docs.map((doc) => ({ id: doc.id }));

            for (const moduleDocument of moduleDocuments) {
            const timeslotsRef = modulesRef.doc(moduleDocument.id).collection('timeslots');
            const timeslotsQuery = timeslotsRef.where('length', '!=', -1);
            const timeslotsQuerySnap = await timeslotsQuery.get();
            const timeslotDocuments = timeslotsQuerySnap.docs.map((doc) => ({ id: doc.id, data: doc.data() }));
            
                for (const timeslotDocument of timeslotDocuments) {
                    array.push(Object.assign(timeslotDocument.data, {id: timeslotDocument.id, modID: moduleDocument.id}))
                }
            }
            return ({ data: array });
        }
    }

    return getData()
    .then((response) => { 
        // console.log(response);
        return response;
    });
}

The Reference page for Firestore reveals the docs property on the snapshot.

Upon running the code, here's the output:

{
  data: [
    {
      length: 1,
      id: '8UIlspnvelEkCUauZtWv',
      modID: 'RmL5BWhKswEuMWytTIvZ'
    },
    {
      title: 'Modules',
      length: 120,
      day: 1,
      startTime: 720,
      id: 'E5fjoGPyMswOeq8mDjz2',
      modID: 'qa15lWTJMjkEvOU74N1j'
    },
    {
      startTime: 360,
      title: 'English',
      day: 2,
      length: 240,
      id: '7JHtPSO83flO3nFOc0aE',
      modID: 'qa15lWTJMjkEvOU74N1j'
    }
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM