简体   繁体   English

获取查询后的Firebase运行集查询

[英]Firebase run set query after get query

Since firebase runs async, how could i run a set query after receiving data from get query and checking if it exists before set? 由于firebase异步运行,我如何在从get查询中接收数据并在设置之前检查它是否存在之后运行set查询?

  var db = firebase.firestore();
  db.settings({});
  const usersRef = db.collection('users').doc(user.uid)

  usersRef.get()
    .then((docSnapshot) => {
      if (!docSnapshot.exists) {
        usersRef.set({
          name: '',
          email: '',
        })
          .then(function() {
            console.log("Document successfully written!");
          })
          .catch(function(error) {
            console.error("Error writing document: ", error);
          });
      }
    });

Thanks in advance 提前致谢

If this is async, you can use async and await. 如果这是异步的,则可以使用异步并等待。

firebasefunc = async () => {
     var db = firebase.firestore();
  db.settings({});
  const usersRef = db.collection('users').doc(user.uid)
   let docSnapshot = await usersRef.get()
   if (!docSnapshot.exists) {
     await usersRef.set({name: '', email: ''})
   }
}

You should return the Promise returned by the set() method, in order to correctly chain your promises. 您应该返回set()方法返回的Promise,以便正确地链接您的Promise。

With your code, the set() is most probably executed but you don't see the console.log("Document successfully written!"); 使用您的代码,最有可能执行set()但是您看不到console.log("Document successfully written!");

Finally, note that you should treat the case when the snapshot does exist, by, for example, throwing an Error. 最后,请注意,当快照确实存在时,应处理这种情况,例如,抛出错误。

So the following code should do the trick: 因此,以下代码可以解决问题:

usersRef.get()
    .then((docSnapshot) => {
        if (!docSnapshot.exists) {
            return usersRef.set({
                name: '',
                email: '',
            });
        } else {
            throw new Error("Document already exists");
        }
    })
    .then(function () {
        console.log("Document successfully written!");
    })
    .catch(function (error) {
        console.error("Error writing document: ", error);
    });

From your comment it seems that you're calling this code from somewhere, that then should take some follow up action before continuing to perform another action (like changing the screen). 从您的评论看来,您似乎是从某个地方调用此代码,然后应该在继续执行其他操作(如更改屏幕)之前采取一些后续措施。

To do that, you'll want to return a promise from the method, so that the caller can wait for the get and set to complete: 为此,您需要从方法中返回一个Promise,以便调用者可以等待getset完成:

function writeUserDocIfNonExistent() {
  return usersRef.get()
    .then((docSnapshot) => {
      if (!docSnapshot.exists) {
        return usersRef.set({
          name: '',
          email: '',
        })
          .then(function() {
            console.log("Document successfully written!");
          })
          .catch(function(error) {
            console.error("Error writing document: ", error);
          });
      }
      else {
        return true
      }
    });
}

Now you can call this function, and do something after the database operations have completed with: 现在,您可以调用此函数,并在数据库操作完成后执行以下操作:

writeUserDocIfNonExistent().then(function() {
  console.log("All database interaction is done, let's go...");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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