search

Home  >  Q&A  >  body text

html5 - Problems encountered in javascript asynchronous programming books?

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

天蓬老师天蓬老师2816 days ago533

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:44:47

    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

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:44:47

    Have you defined the url? - -

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 13:44:47

    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?

    reply
    0
  • Cancelreply