TypeError:无法读取未定义的属性'then'

Eze*_*wei 89 javascript promise angularjs

loginService.islogged() 
Run Code Online (Sandbox Code Playgroud)

上面的函数返回一个像"失败"的字符串.但是,当我尝试运行然后函数,它将返回错误

TypeError: Cannot read property 'then' of undefined
Run Code Online (Sandbox Code Playgroud)

并且光标在connected之前和之后指示.then.

以下是完整功能:

var connected=loginService.islogged();
alert(connected);
connected.then(function(msg){
    alert("connected value is "+connected);
    alert("msg.data value is "+msg.data);
    if(!msg.data.account_session || loginService.islogged()=="failed")       
        $location.path('/login');
});
Run Code Online (Sandbox Code Playgroud)

UPDATE

这是islogged()功能

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
        return $checkSessionServer;
    });
}
Run Code Online (Sandbox Code Playgroud)

我确信这$checkSessionServer会导致"失败"的字符串.而已.

The*_*One 120

您需要将您的承诺返回给调用函数.

islogged:function(){
    var cUid=sessionService.get('uid');
    alert("in loginServce, cuid is "+cUid);
    var $checkSessionServer=$http.post('data/check_session.php?cUid='+cUid);
    $checkSessionServer.then(function(){
        alert("session check returned!");
        console.log("checkSessionServer is "+$checkSessionServer);
    });
    return $checkSessionServer; // <-- return your promise to the calling function
}
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是我工厂没有退回承诺的原因.我忘了做`return $ http.post`.一旦我将前缀`return`添加到`$ http`,它就开始正常工作了. (3认同)
  • @Devner谢谢你,我也忘记了传递`return`. (2认同)