异步函数中的Javascript全局变量?

时间:2016-07-06 07:37:21

标签: javascript

我想从asycn函数的结果中创建一个全局变量_userRegister。怎么做?

    /* Socket.io-client Function */

    function reportSignUp(socket, date) {
       // sent to socket server
        socket.emit('report signup', date);

       // listenning response from server 
        socket.on('users signup', function (data) {
           // data is the result from server
            console.log('user register', data);


           // make data global
           _userRegister = data;
        });
    }
    ;

    /* End Socket.io-client Function */

    $(function () {


        var _userRegister;

        var socket = io();

        var date = getDateTime(); // get current time from system

        reportSignUp(socket, date);

        console.log("_userRegister",_userRegister); // <- underfine
    });

</script>

2 个答案:

答案 0 :(得分:3)

让你的函数返回一个promise。如果您需要在其他地方访问此异步值,您也可以在全局范围内保存承诺。

function reportSignUp(socket, date) {
   var dfd = $.Deferred();
   // sent to socket server
    socket.emit('report signup', date);

   // listenning response from server 
    socket.on('users signup', function (data) {
       // data is the result from server
        console.log('user register', data);


       dfd.resolve(data);
    });

    return _userRegistering = dfd.promise();
}

/* End Socket.io-client Function */

$(function () {


    var _userRegister;

    var socket = io();

    var date = getDateTime(); // get current time from system

    reportSignUp(socket, date).then(function(userData) {
        console.log("_userRegister", userData); 
    });

    // or

    _userRegistering.then(function(userData) {
        console.log("_userRegister from global variable", userData); 
    })
});

答案 1 :(得分:0)

使用诺言是好的。

但你也可以通过使用回调函数控制执行流来尝试这个:

function reportSignUp(socket, date, onSignupCallback) {
       // sent to socket server
        socket.emit('report signup', date);

   // listenning response from server 
    socket.on('users signup', function (data) {
       // data is the result from server
        console.log('user register', data);

       // make data global
       //_userRegister = data;
       if(onSignupCallback) onSignupCallback(data);
    });
}

然后

$(function () {


    var _userRegister;

    var socket = io();

    var date = getDateTime(); // get current time from system

    reportSignUp(socket, date, function(data){
        console.log("_userRegister", userData); 
    });

});