-
-
Save tmslnz/04a2b9280563df6b4030 to your computer and use it in GitHub Desktop.
A most simple promise system, to explain promises
This file contains hidden or 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