Last active
September 28, 2015 11:28
-
-
Save cefn/c847bae4a5c372755498 to your computer and use it in GitHub Desktop.
A way to enable Kefir streams to implement a timeout on the next event. Modified to improve timeout handling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Kefir = require("kefir"); | |
var period = 1000; | |
//var wait = 2 * period; //success condition | |
var wait = 0.5 * period; //failure condition | |
function promiseNextBefore(stream, timeout){ | |
return new Promise(function(resolve, reject){ | |
function handler(event){ | |
if(event.type==="value"){ | |
resolve(event.value); | |
} | |
else{ | |
reject(event); | |
} | |
unsubscribe(); | |
} | |
var timeoutId = setTimeout(function(){ | |
if(handler){ | |
unsubscribe(); | |
reject("Promise of next event timed out after " + timeout); | |
} | |
}, timeout); | |
function unsubscribe(){ | |
if(timeoutId){ | |
stream.offAny(handler); | |
clearTimeout(timeoutId); | |
timeoutId = null; | |
} | |
} | |
stream.onAny(handler); | |
}); | |
} | |
var promise = promiseNextBefore(Kefir.interval(period, "Hello World"), wait).then( | |
function(value){ console.log("Succeeded with " + value); }, | |
function(err){ console.log("Failed with " + err.toString()); } | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment