@goldaxe/listening-socket-as-promise
Version:
npm login
27 lines (26 loc) • 1.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Allows you to connect to a relatively generic event and make a promise out of it. It is possible to specific
* a validator to filter the result, as soon as a result matches the promise is resolved with the object received and ready
* in use. In case more than timeoutInMillis ms have elapsed, reject the promise.
*/
function listeningSocketAsPromiseUtil(socket, eventName, validator, timeoutInMillis) {
const defaultTimeoutInMillis = 60000; // 60s
return new Promise((resolve, reject) => {
const eventTimeout = setTimeout(() => {
reject("Timeout event");
socket.off(eventName, listener);
}, timeoutInMillis !== undefined ? timeoutInMillis : defaultTimeoutInMillis);
function listener(eventObj) {
if (!(validator === null || validator === void 0 ? void 0 : validator(eventObj))) {
return;
}
resolve(eventObj);
clearTimeout(eventTimeout);
socket.off(eventName, listener);
}
socket.on(eventName, listener);
});
}
exports.default = listeningSocketAsPromiseUtil;