首页 > 解决方案 > 在 Javascript 中检查结果时如何修复“未定义”对象?

问题描述

所以我遇到了在代码顶部定义的变量(结果)的问题,但是一旦我稍后控制台记录它,它就会返回为未定义。我正在设置一个时事通讯表单,这是检查用户是否已经注册的逻辑,并弹出一条关于他们是否注册的消息。

我试图将变量设置为布尔值,但代码正在检查特定的用户输入,所以这不起作用,我也尝试在代码的不同部分设置变量,但没有运气。不幸的是,当谈到 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)
      })

预期的结果是结果变量应该控制台记录用户输入的电子邮件,以便我可以检查它的某些特征,但是当我控制台记录它时我得到一个未定义的结果。对此有什么想法吗?

标签: javascriptfirebase

解决方案


coll.doc(email) 可能会失败并且结果保持为空值,您应该在调用 coll.doc(email) 之前尝试为 var result 赋值;像这样:

var whatevervar = "";

或者如果是一个整数:

var whatevervar = 0;

of if 是一个布尔值:

var whatevervar = false;

ETC...

像这样:

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)
      })

推荐阅读