问题描述
我有一个回调处理程序来处理websocket事件,并且我正在尝试编写一个将返回诺言的函数.如果调用了处理程序,则应解决promise;如果未执行处理程序,则应拒绝.有更好的方法吗?
I have a callback handler to handle a websocket event and I am trying to write a function which would return a promise. The promise should be resolved if the handler is called or rejected if the handler is not executed. Is there a better way to do this?
var callbackCalled = false;
var message = null;
waitForMessage = function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (callbackCalled) {
callbackCalled = false;
message = null;
resolve();
} else {
reject();
}
}, 5000);
});
}
onEvent = function(event) {
console.log("Process the event");
//set the message
callbackCalled = true;
};
推荐答案
您可以使用类似这样的东西.这将拒绝在传入事件之前发生超时.如果事件在超时之前发生,它将使用数据进行解析.
You could use something like this. This will reject is the timeout happens before the incoming event. It will resolve with data if the event happens before the timeout.
function waitForEventWithTimeout(socket, event, t) {
return new Promise(function(resolve, reject) {
var timer;
function listener(data) {
clearTimeout(timer);
socket.removeListener(event, listener);
resolve(data);
}
socket.on(event, listener);
timer = setTimeout(function() {
socket.removeListener(event, listener);
reject(new Error("timeout"));
}, t);
});
}
您将像这样使用它:
waitForEventWithTimeout(socket, "myEvent", 1000).then(function(data) {
// got data here
}, function() {
// timeout here
});
请注意,我在此处添加和删除事件侦听器,以确保它不会被处理太多或添加太多次,因为事件处理程序是多镜头侦听器,但是诺言是一发.
Note, I add and remove the event listener here to make sure it's not processed too many times or added too many times because event handlers are multi-shot listeners, but promises are one shot.
这篇关于在Node.js中承诺事件处理程序和超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!