[英]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.它在
if (docSnapshot.exists) {
之后返回 true,但在 function 的最后一个返回 false。
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. function
checkIfSeen
没有明确的返回类型。 It will always return undefined
to who ever calls it.它总是会返回
undefined
给调用它的人。
And also there is an asynchronous activity inside the function, at docRef.get()
function 内部还有一个异步活动,位于
docRef.get()
This is something called as a promise.这就是所谓的 promise。 It executes the
then
block when its job is done passing the returned data to the function supplied to the then
function.当它的工作完成时,它执行
then
块,将返回的数据传递给 function 提供给then
function。
The function execution now enters then block and it cannot synchronously return to the outer function. function 执行现在进入 then 块,它不能同步返回到外部 function。
You can continue execution of your program inside the then function.您可以在 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.