Last active
August 29, 2015 14:22
-
-
Save rc1/b556844e290997b447e4 to your computer and use it in GitHub Desktop.
Simple Promise System
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
// 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