简体   繁体   中英

Why does this function return false in React Native?

funciton

checkIfSeen = (uid, news_id) => {
  var seen = false;
  const docRef = DB.informationsCollection.doc(news_id).collection('users').doc(uid);
  docRef.get()
    .then((docSnapshot) => {
      if (docSnapshot.exists) {
        seen = true;
        console.log(seen);
        // returns true
      }
    });
  console.log(seen);
  // returns false
}

Problem

It returns true after if (docSnapshot.exists) { but returns false in the last of the function.

Does anybody know why this happens?

I would appreciate it if you could give me any adivce.

updated

checkIfSeen = (uid, news_id) => {
  const docRef = Fire.shared.informationsCollection.doc(news_id).collection('users').doc(uid);
  docRef.get()
    .then((docSnapshot) => {
      if (docSnapshot.exists) {
        this.alreadySeen();
      } else {
        this.notSeen();
      }
    });
}

alreadySeen = () => {
  return true;
}

notSeen = () => {
  return false;
}

The function checkIfSeen has no explicit return type. It will always return undefined to who ever calls it.

And also there is an asynchronous activity inside the function, at docRef.get()

This is something called as a promise. It executes the then block when its job is done passing the returned data to the function supplied to the then function.

The function execution now enters then block and it cannot synchronously return to the outer function.

You can continue execution of your program inside the then function. like

checkIfSeen = (uid, news_id) => {
  var seen = false;
  const docRef = DB.informationsCollection.doc(news_id).collection('users').doc(uid);
  docRef.get()
    .then((docSnapshot) => {
      if (docSnapshot.exists) {
        seen = true;

        // Do something here or invoke any other function
        renderUI();
        console.log(seen);
        // returns true
      }
    });
  console.log(seen);
  // returns false
}

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