Skip to content

Instantly share code, notes, and snippets.

@cefn
Last active September 28, 2015 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cefn/c847bae4a5c372755498 to your computer and use it in GitHub Desktop.
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.
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