首页 > 解决方案 > 如何等待从 Cloud Firestore 中获取数据,然后在 NodeJS 中返回它们?

问题描述

我想从 Cloud Firestore 中获取一些数据,然后在地图中返回该数据。问题是系统在获取该值之前返回该值并且承诺处于未决状态。我尝试了很多东西,但无法解决问题。如果有人可以帮助我,那就太好了!

function homepage(formData) {
    var cfire = cfirebase.firestore().collection('Details').doc('dsadsadasdsadasdsdsdasd');

    const test = cfire.get().then(doc => {
        if (doc.exists) {
            Name = doc.data().dd.dn;
            vehical = doc.data().dd.vn;
            vehicalNumber = doc.data().dd.vno;
            console.log(Name, vehical, vehicalNumber);
        } else if (!doc.exists) {
            console.log("Detail does not exist");
            return Promise.reject(new Error('Detail does not exist'));
        } else {
            throw Promise.reject(new Error('Server error!'));
        }
    }).catch(e => {
        return false
    });
    return {
        tripID: {
            c: false,

            dd: {
                // Driver name 
                dn: Name,
                // Vehical name
                vn: vehical,
                // Vehical number
                vno: vehicalNumber,
            }
        }
    };
}

标签: node.jsgoogle-cloud-firestoregoogle-cloud-functions

解决方案


The reason why your function returns the object before you fetch data from cloud firestore is because cfirebase.firestore().collection(...).doc(...) is asynchronous and it returns a Promise, so you have to wait for that Promise to resolve before you return the final object.

You should read up on asynchronous programming if you're not familiar with the concept:

I suggest you change your homepage function so that it returns a Promise or utilize async/await to wait for cfire.get() to resolve with some value before you return the final object.

Option #1

function homepage(formData) {
  const cfire = cfirebase.firestore().collection(...).doc(...)

  return cfire.get()
    .then(doc => {
      if (!doc) {
        throw new Error("Server error")
      }
      if (!doc.exists) {
        throw new Error("Details does not exist")
      }
      // ...
      return { Name, vehical, vehicalNumber }
    })
    .then(result => {
      // result => { Name, vehical, vehicalNumber }
      // ...
      return {
        tripId: {...}
      }
    })
}
// then
homepage(...)
  .then(result => {...})
  .catch(error => {...})

Option #2

To use async/await, you have to have Node.js 8.x or higher.

async function homepage(formData) {
  try {
    const cfire = cfirebase.firestore().collection(...).doc(...)

    const doc = await cfire.get()

    if (!doc) {
      throw new Error("Server error")
    }

    if (!doc.exists) {
      throw new Error("Details does not exist")
    }

    // ...
    return {
      tripID: {...}
    }
  } catch(error) {
    throw error
  }
}
// then
homepage(...)
  .then(result => {...})
  .catch(error => {...})

Read more about async/await:

Hope this helps.


推荐阅读