Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Last active September 30, 2016 13:10
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 kevincennis/130cdd4ea333bbc9edca5ebd1f2c4dfd to your computer and use it in GitHub Desktop.
Save kevincennis/130cdd4ea333bbc9edca5ebd1f2c4dfd to your computer and use it in GitHub Desktop.
Tiny co shim
module.exports = function( fn, ...args ) {
return new Promise( ( resolve, reject ) => {
const it = fn.apply( this, args );
const [ yay, boo ] = [ 'next', 'throw' ].map( factory );
yay();
function factory( method ) {
return function( res ) {
try {
const { done, value } = it[ method ]( res );
done ? resolve( value ) : value.then( yay, boo );
} catch ( err ) {
return reject( err );
}
}
}
});
};
const c = require('./lib/c');
const wait = n => new Promise( resolve => setTimeout( resolve, n ) );
c(function*() {
let count = 0;
while ( true ) {
console.log( count++ );
yield wait( 1000 );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment