[英]Adding a timeout for a callback within a promise and rejecting
I'm converting socket.io's emit function to a promise like this. 我正在将socket.io的发射函数转换为这样的承诺。
var io = require("socket.io-client")
var Promise = require("bluebird")
var _ = require("underscore")
io.emitAsync = function(event, payload){
return new Promise(function (resolve, reject) {
return io.emit(event, payload, function(){
var args = _.toArray(arguments)
if(args[0]) reject(new Error(args[0]))
resolve.apply(null, args)
})
})
}
I couldn't use promiseify
because the io.emit
callback doesn't return a node-style callback signature. 我不能使用
promiseify
因为io.emit
回调不返回节点样式的回调签名。 The first argument can't be an error object. 第一个参数不能是错误对象。 So the plan is to pass a string error message, the promise above will reject if the first argument is
truthy
. 因此,计划是传递一个字符串错误消息,如果第一个参数为
truthy
,则上面的promise将拒绝。 This is all fine and dandy, here's the problem. 一切都很好,这就是问题所在。
If you don't return a callback
in your socket.on
then this promise above will never resolve
or reject
anything. 如果您没有在
socket.on
返回callback
,那么上述承诺将永远不会resolve
或reject
任何事情。 So what I need is a timeout this callback
, if nothing comes back within an allotted period of time then it will reject(new Error("timeout"))
. 因此,我需要的是使此
callback
超时,如果在指定的时间内没有任何响应,则它将reject(new Error("timeout"))
。 Thing is I have no clue how to do that. 我不知道该怎么做。 Ideally I can set the
seconds
to wait within the function above, or if know there's no callback for a given event I'd want to resolve
, so ideally it's a parameter of emitAsync
itself. 理想情况下,我可以在上面的函数中设置等待的
seconds
,或者如果知道我想resolve
的给定事件没有回调,那么理想情况下,它是emitAsync
本身的参数。 Thoughts? 有什么想法吗?
You could just use the Bluebird timeout
method of course… 您当然可以使用Bluebird
timeout
方法 …
The lower-level solution would be to use setTimeout
: 下层解决方案是使用
setTimeout
:
new Promise(function (resolve, reject) {
io.emit(event, payload, function(err){
if(err) reject(new Error(err))
resolve(_.toArray(arguments).slice(1));
})
setTimeout(function(){
reject(new Error("timeout"));
}, seconds*1000);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.