简体   繁体   中英

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?

  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.

With your code, the set() is most probably executed but you don't see the 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:

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...");
});

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