JS回调returns undefined 不是函数
JS callback returns undefined is not a function
我以为我知道如何实现回调,这就是我所拥有的:
index.html:
socket.on('userCapture', data, function(callback){
if(callback){
//do stuff
} else {
alert('Username in use.');
}
});
index.js:
socket.on('userCapture', function(data, callback){
username = data.username;
question = data.question;
socket.username = username;
socket.room = username;
function isInArray(arr,obj) {
return (arr.indexOf(obj) != -1);
}
if(isInArray(usernames, username)){
callback(false);
} else {
callback(true);
}
});
我的想法是检查用户名数组中传递的值,如果它存在或不存在则返回给客户端。我不明白为什么它会导致未定义,因为我在其他地方有完全相同的代码并且它有效..
此致
您正在为 socket.on()
指定回调,您不能这样做。
根据 Socket.io docs,可以使用 emit()
或 send()
进行回调,因为您基本上想发送一条消息,然后检索结果而无需编写不同的 socket.on()
.
更改代码以使用 emit()
客户代码
socket.emit('userCapture', data, function(response){
if(response){
//do stuff
} else {
alert('Username in use.');
}
});
服务器代码
socket.on('userCapture', function(data, callback){
username = data.username;
question = data.question;
socket.username = username;
socket.room = username;
function isInArray(arr,obj) {
return (arr.indexOf(obj) != -1);
}
// you can just send the result back
callback(isInArray(usernames, username));
});
我以为我知道如何实现回调,这就是我所拥有的:
index.html:
socket.on('userCapture', data, function(callback){
if(callback){
//do stuff
} else {
alert('Username in use.');
}
});
index.js:
socket.on('userCapture', function(data, callback){
username = data.username;
question = data.question;
socket.username = username;
socket.room = username;
function isInArray(arr,obj) {
return (arr.indexOf(obj) != -1);
}
if(isInArray(usernames, username)){
callback(false);
} else {
callback(true);
}
});
我的想法是检查用户名数组中传递的值,如果它存在或不存在则返回给客户端。我不明白为什么它会导致未定义,因为我在其他地方有完全相同的代码并且它有效..
此致
您正在为 socket.on()
指定回调,您不能这样做。
根据 Socket.io docs,可以使用 emit()
或 send()
进行回调,因为您基本上想发送一条消息,然后检索结果而无需编写不同的 socket.on()
.
更改代码以使用 emit()
客户代码
socket.emit('userCapture', data, function(response){
if(response){
//do stuff
} else {
alert('Username in use.');
}
});
服务器代码
socket.on('userCapture', function(data, callback){
username = data.username;
question = data.question;
socket.username = username;
socket.room = username;
function isInArray(arr,obj) {
return (arr.indexOf(obj) != -1);
}
// you can just send the result back
callback(isInArray(usernames, username));
});