Created
September 27, 2020 16:28
-
-
Save zachsa/9f247b96a6e72927b6f3e15bfe1161a8 to your computer and use it in GitHub Desktop.
Looking at the logic of what constitutes a JavaScript promise - I can see that it is a way of separating out callbacks from asynchronous code
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
function P (cb) { | |
var _nextFn | |
var _catchFn | |
/** | |
* User registers a callback via | |
* the 'then()' instance fn | |
*/ | |
this.then = function (cb) { | |
_nextFn = cb | |
return this | |
} | |
/** | |
* User registers an error handler | |
* via the 'catch()' instance fn | |
*/ | |
this.catch = function (cb) { | |
_catchFn = cb | |
return this | |
} | |
/** | |
* User signals that the registered callback | |
* must not be executed, and the user provides | |
* a value to pass to that callback | |
*/ | |
function resolve (value) { | |
try { | |
_nextFn(value) | |
} catch (error) { | |
_catchFn(error) | |
} | |
} | |
/** | |
* If an error is thrown then the registered | |
* error handler should be invoked | |
*/ | |
function reject (error) { | |
_catchFn(error) | |
} | |
cb(resolve, reject) | |
} | |
const p = new P( resolve => setTimeout(() => resolve('Some Value'), 1000) ) | |
p.then( value => { throw new Error (value) } ) | |
p.catch( error => console.log('Error caught:', error.message)) | |
console.log('The End') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment