How to wait for the promise when using get in Firestore

主宰稳场 提交于 2019-12-02 09:04:04

You have 2 options: you can use async/await or you can use Promise.then() depending on how you want the code to execute.

Async/await:

async function databasetest {
  var cityRef;
  try{
    cityRef = await db.collection('cities').doc('SF');
    // do stuff
  } catch(e) {
    // error!
  }

Promise.then():

db.collection('cities').doc('SF').then((cityRef) => {
  cityRef.get()
    .then(doc => { /* do stuff */ })
    .catch(err => { /* error! */ });
});

maybe a little of work around could help you, I'm not sure yet how you are trying to implement it.

 function databasetest () {
  var cityRef = db.collection('cities').doc('SF');
  return cityRef.get()
  }

// so you can implement it like

databasetest().then(doc => {
 if (!doc.exists) {
   console.log('No such document!');
 } else {
   console.log('Document data:', doc.data());
 }
})
.catch(err => {
  console.log('Error getting document', err);
});

More context would help to understand your use case better :)

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