我遇到以下问题。我想将客户端的所有 socket.emit 函数分离到一个单独的 Controller 类中,以便我可以调用 Controller 函数并接收响应:
应用程序/组件/client.js
let response = NodeController.root(path);
console.log('response', response);
if(response){
var projectInfoId = JSON.parse(response);
}
app/controller/node-controller.js
class NodeController {
static root(data){
let tmp;
socket.emit('/', data, function (response) {
tmp = response;
});
return tmp;
}
}
client.js 中的projectInfoId 将是未定义的,因为响应未定义。如果我使用回调函数直接在客户端中调用 socket.emit() ,我将收到数据并且我的 projectInfoId 将包含一些内容。
是否可以将套接字函数与 client.js 代码分开,还是必须直接在 client.js 文件中调用它?
最佳答案
这是尝试在异步函数上使用 return 的典型案例。正确的方法是在根函数上添加回调,如下所示:
class NodeController {
static root(data, callback){
let tmp;
socket.emit('/', data, function (response) {
tmp = response;
callback(tmp);
});
}
}
然后像这样使用它:
let response = NodeController.root(path, function(response){
console.log('response', response);
if(response){
var projectInfoId = JSON.parse(response);
}
});
还有一些其他方法可以处理异步函数。其中之一是 async.js npm 模块(是的,它可以在客户端上工作),使用函数生成器甚至使用 Promise。
关于javascript - 在外部 Controller 客户端使用socketIO.emit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44287523/