再看JavaScript异步编程这本书,然后看到了一段代码
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;
};
书中说
var socket=openWebSocket(url,function(){
socket.send('Hello,server!');
});
这样会使代码崩溃,不解。。在返回值之前调用回调函数为什么会使代码崩溃。希望大大们能帮我解释解释
漂亮男人2017-05-16 13:44:47
const func = function (callback) {
callback();
return 100;
};
const x = func(() => {
console.log(x); //此处将打印 undefined;
});
console.log(x); //此处打印 100
这样解释不知道你能否明白?