-
-
Save kevincennis/130cdd4ea333bbc9edca5ebd1f2c4dfd to your computer and use it in GitHub Desktop.
Tiny co shim
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
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 ); | |
} | |
} | |
} | |
}); | |
}; |
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
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