[英]AngularJS $q promise with socket.io
I would like to create an angularJS promise which works with socket.io. 我想创建一个与socket.io一起使用的angularJS promise。 I have currently a callback set to deal with the response : 我目前有一个回调集来处理响应:
function request(event, data, callback) {
socket.emit(event, data);
socket.on(event, function(d) {
socket.off(event);
callback(d);
});
}
This force me to write something like : 这迫使我写类似:
request('myEvent', 'Hello World !', function(data) {
...
});
I wonder if we could use a promise (with $q service from angular) : 我想知道我们是否可以使用promise(来自angular的$ q服务):
request('myEvent', 'Hello World !').then(function(data) {
});
Thanks ! 谢谢 !
You can try something like 您可以尝试类似
function request(event, data) {
var deferred = $q.defer();
socket.emit(event, data);
socket.on(event, function(d) {
socket.off(event);
deferred.resolve(d);
});
return deferred.promise;
}
Then you can use 那你可以用
request('myEvent', 'Hello World !').then(function(data) {
});
function request (eventName, data) {
return $q(function (resolve, reject) {
socket.emit(eventName, data);
socket.on(eventName, function (data) {
socket.off(eventName);
resolve(data);
});
});
}
well promises can only resolve or reject ones. 好诺言只能解决或拒绝诺言。 will the event happened more then once ? 事件会再发生一次吗? do you care if it happened more then ones 你在乎它是否发生过
If your ok with your event firing only 1 time then you can promise it yea. 如果您的事件只触发1次,那么您可以答应。
function request(event, data, callback) {
socket.emit(event, data);
socket.on(event, function(d) {
socket.off(event);
callback(d);
});
}
becomes: 变为:
function request(event, data) {
return $q(function(resolve, reject) {
socket.emit(event, data);
socket.on(event, function(d) {
socket.off(event);
resolve(d)
});
});
}
You will use it: 您将使用它:
request('event', data).then(....)
I had the problem when I wrap socket.on(event) in a function and call the function more than onceit will open multiple of them. 当我将socket.on(event)包装在函数中并多次调用该函数时,我遇到了问题,它将打开多个函数。 So the socket.on(event) is called multiple times when the backend calls a specific socket event. 因此,当后端调用特定的套接字事件时,将多次调用socket.on(event)。 If fixed this by using $rootScope.$on which only can have one instance. 如果通过使用$ rootScope。$ on来解决此问题,则只能有一个实例。
this.search = (query) => {
var deferred = $q.defer();
socket.emit('search', {query: query}) // send data to backend
$rootScope.$on('search', function(event,data){
deferred.resolve(data);
});
return deferred.promise;
}
//get data back from backend
socket.on('search',(data) => {
$rootScope.$emit('search',data);
});
The hole code is wrapped inside an Angularjs service. 漏洞代码包装在Angularjs服务中。 To get the data now from the socket.on('search') you can do something like this: 要立即从socket.on('search')获取数据,您可以执行以下操作:
SocketioService.search('Some query').then( (data) => {
//do something with the data from the backend
})
Not sure if this is the best solution, but it works :) 不知道这是否是最好的解决方案,但是它可以工作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.