html5 - Problems encountered in javascript asynchronous programming books?
天蓬老师
天蓬老师 2017-05-16 13:42:47
0
3
504

Read the book JavaScript Asynchronous Programming again, and then I saw a piece of code

var webSocketCache = {};
function openWebSocket(serverAddress, callback) {
    var socket;
    if (serverAddress in webSocketCache) {
        socket = webSocketCache[serverAddress];
        if (socket.readyState === WebSocket.OPEN) {
            callback();
        } else {
            socket.onopen = _.compose(callback, socket.onopen);
        };
    } else {
        socket = new WebSocket(serverAddress);
        webSocketCache[serverAddress] = socket;
        socket.onopen = callback;
    };
    return socket;
};

The book says

        var socket=openWebSocket(url,function(){
          socket.send('Hello,server!');      
        });

This will cause the code to crash, which is confusing. . Why does calling a callback function before returning a value crash the code. I hope you guys can help me explain

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
Peter_Zhu

The callback function may be executed before returning, and the socket at this time has not been assigned a value

You can pass a parameter to the callback to avoid this situation

巴扎黑

Have you defined the url? - -

漂亮男人
const func = function (callback) {
    callback();
    return 100;
};

const x = func(() => {
    console.log(x); //此处将打印 undefined;
});

console.log(x); //此处打印 100

I wonder if you can understand this explanation?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template