在异步函数中调用函数javascript(Meteor)获取未定义

时间:2014-02-27 18:34:28

标签: javascript jquery asynchronous meteor

问题似乎是调用函数vote_ipcheck()vote_cookie_check()都会抛出错误Uncaught TypeError: undefined is not a function。如果我将函数的内容放在$.getJSON call内,那么这不是问题,但是调用函数会抛出该错误。

如果有人知道为什么会发生这样的事情,那就太棒了。

    if (ip_check) {
        $.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){

            console.log(data.host);

            var vote_ipcheck = vote_ipcheck(data.host);
            var vote_cookie_check = vote_cookie_check();

            if (vote_ipcheck && vote_cookie_check) {
                Router.go('pollyResults', {_id: id});
            } else if (vote_ipcheck == false && vote_cookie_check == false) {
                update_poll();
            }

        });
    }

    function vote_cookie_check() {
      // Handling the cookie business
      console.log(ReactiveCookie.list());

      if (ReactiveCookie.get('voted')) {
        var object_voted = JSON.parse(ReactiveCookie.get('voted'));
        if (id in object_voted) {
            if (object_voted[id] == true) {
                    return true;
            }
        } else {
            object_voted[id] = true;
            ReactiveCookie.set('voted', JSON.stringify(object_voted), {days: 365});
            return false;
        }
      } else {
            var object_voted = {};
            object_voted[id] = true;
            ReactiveCookie.set('voted', JSON.stringify(object_voted), {days: 365});
            return false;
      }
    }

    function vote_ipcheck(ip) {
        ip_voted = ip_array.indexOf(ip);

        if (ip_voted > -1) {
            return true;
        }
        else {
            Polls.update({_id: id}, {$push : {already_voted : ip}});
            return false;           
        }
    }

1 个答案:

答案 0 :(得分:1)

如果要使用具有这些名称的全局函数,请不要在本地范围内重新定义vote_ipcheckvote_cookie_check。为局部变量赋予不同的名称。

        var ipcheck = vote_ipcheck(data.host);
        var cookie_check = vote_cookie_check();

        if (ipcheck && cookie_check) {
            Router.go('pollyResults', {_id: id});
        } else if (ipcheck == false && cookie_check == false) {
            update_poll();
        }