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
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? - -
I wonder if you can understand this explanation?