Skip to content

Instantly share code, notes, and snippets.

@zachsa
Created September 27, 2020 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachsa/9f247b96a6e72927b6f3e15bfe1161a8 to your computer and use it in GitHub Desktop.
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
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