Skip to content

Instantly share code, notes, and snippets.

@rc1
Last active August 29, 2015 14:22
Show Gist options
  • Save rc1/b556844e290997b447e4 to your computer and use it in GitHub Desktop.
Save rc1/b556844e290997b447e4 to your computer and use it in GitHub Desktop.
Simple Promise System
// A most simple promise system, to explain promises
var p = promise( function ( resolve, reject ) {
// do async stuff here
fs.readFile( function ( err, file ) {
if ( err ) {
reject( new Error( 'it mucked up' ) );
} else {
resolve( file );
}
});
});
p.success( function ( value ) {
console.log( 'I got the value', v );
});
p.error( function ( err ) {
console.log( 'It failed', err );
throw err;
});
function promise ( fn ) {
var onSuccess = function () {};
var onError = function () {};
setTimeout( function () {
fn( function () {
onSuccess.apply( this, arguments );
}, function () {
onError.apply( this, arguments );
});
}, 0 );
return {
success: function ( fn ) { onSuccess = fn; },
error: function ( fn ) { onError = fn; }
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment