所以我遇到了在代码顶部定义的变量(结果)的问题,但是一旦我登录控制台,它稍后就会以未定义的形式返回。我正在设置新闻稿表单,这是检查用户是否已经注册并弹出一条有关他们是否已注册的消息的逻辑。
我尝试将变量设置为布尔值,但是代码正在检查特定的用户输入,因此这行不通,我还尝试了在代码的不同部分设置变量,但是没有运气。不幸的是,关于javascript,我还是一个新手。
var result = coll.doc(email);
exists.then(val => {
console.log(val)
// perform an action according to existing document or not
if (val == true) { // document already exists
alert("already registered to our newsletter. Thank you for your interest!");
console.log(message)
} else if (val == false) { // document doesn't exist
console.log('setting the doc');
// set the new document
coll.doc(email).set({
firstname: firstName,
lastname: lastName,
nation: country,
type: typeofInv
})
.then(result => { // if no error
console.log('Received ticket: ' + result);
if (result) { // check for certain characteristics in the result here
alert("You are successfully registered. We will be in touch!");
}
console.log(message)
})
预期结果是结果变量应该控制台记录用户输入的电子邮件,以便我可以对照它检查某些特征,但是当我对其进行控制台记录时,却得到了未定义的结果。有什么想法吗?
答案 0 :(得分:0)
coll.doc(email)可能会失败并且结果保持为空值,您应该在调用coll.doc(email)之前尝试为var result赋予一个值;像这样:
var whatevervar = "";
或者如果是整数:
var whatevervar = 0;
of if is a bool:
var whatevervar = false;
等...
就是这样:
var result = "";
result = coll.doc(email);
exists.then(val => {
console.log(val)
// perform an action according to existing document or not
if (val == true) { // document already exists
alert("already registered to our newsletter. Thank you for your interest!");
console.log(message)
} else if (val == false) { // document doesn't exist
console.log('setting the doc');
// set the new document
coll.doc(email).set({
firstname: firstName,
lastname: lastName,
nation: country,
type: typeofInv
})
.then(result => { // if no error
console.log('Received ticket: ' + result);
if (result) { // check for certain characteristics in the result here
alert("You are successfully registered. We will be in touch!");
}
console.log(message)
})