退出函数后var的值会变回空白?

时间:2015-09-22 04:00:47

标签: javascript angularjs http ionic

所以我在一个放在我的服务脚本中的函数内部有一个api请求。我已经定义了变量" curruser"在函数之外所以我可以保持它的值,但是在退出跟随Scirpt后,curruser是空的?

services.js

function fbUserInfo() {
  ngFB.api({
    path: '/me',
    params: {
      fields: '/*params*/'
    }
  }).then(
    function(user) {
      curruser = user;

      $http.get(/*send GET request to my server*/).success(function(response) {
        if (response.length < 20) {
          curruser.firsttime = true;
        } else {
          curruser.firsttime = false;
        }
        console.log(curruser);
        console.log("1");
      });
    },

    function(error) {
      alert('Facebook error: ' + error.error_description);
    });
}

所以console.log会返回我从facebook检索到的正确的JSON对象..但是当我在return语句中返回它时

return {
  userInfo: function() {
    fbUserInfo();
    console.log(curruser);
    return curruser;
  }

它返回curruser是一个空对象!我写了

var curruser;

进入&#34; .factory&#34;

内的第一行

2 个答案:

答案 0 :(得分:0)

你必须使用then(),因为fbUserInfo()是异步函数

Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FolderExists(Write_Dir_Name) Then
   Create_Directory Write_Dir_Name
End If
If Right(Write_File_Name, 4) = ".xml" Then
   Set a = fs.CreateTextFile(Write_Dir_Name & Write_File_Name, True)
Else
   Set a = fs.CreateTextFile(Write_Dir_Name & Write_File_Name & ".xml", True)
End If

'...    
'Writes data to xml file
'...

a.Close

答案 1 :(得分:0)

没有测试过,但可能有用。

    var curruser;
    function fbUserInfo( callback ) {
      ngFB.api({
        path: '/me',
        params: {
          fields: '/*params*/'
        }
      }).then(
        function(user) {
          curruser = user;

          $http.get(/*send GET request to my server*/).success(function(response) {
            if (response.length < 20) {
              curruser.firsttime = true;
            } else {
              curruser.firsttime = false;
            }
            console.log(curruser);
            console.log("1");
            callback(curruser);
          });
        },

        function(error) {
          alert('Facebook error: ' + error.error_description);
        });
    }


return {
  userInfo: function( callback ) {
    fbUserInfo( function(data){
       console.log(data);
       callback(data);
    });
  }