Created
January 27, 2017 16:25
-
-
Save dengjonathan/de7f8976ce1c24924e3ab069d5d5feaf to your computer and use it in GitHub Desktop.
Naive Promise implementation
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
// creates a promise object which will either resolve or reject | |
const Promise = function (executor) { | |
const _thens = []; | |
let _catch; | |
const promise = { | |
then: cb => { | |
_thens.push(cb); | |
return promise; | |
}, | |
catch: errHandlers => { | |
_catch = errHandlers | |
return promise; | |
} | |
} | |
const fulfill = data => { | |
while (_thens.length) { | |
try { | |
data = _thens.shift()(data); | |
} catch (err) { | |
_catch(err); | |
} | |
} | |
}; | |
const reject = err => { | |
if (_catch){ | |
_catch(err); | |
} | |
}; | |
executor(fulfill, reject); | |
return promise; | |
}; | |
// TEST | |
Promise((fulfill, reject) => { | |
setTimeout(() => { | |
if (Math.random() < 0.5) { | |
fulfill('this is the value'); | |
} else { | |
reject('err'); | |
} | |
}, 100) | |
}) | |
.then(val => { | |
console.log(val); | |
return 'i am chainable'; | |
}) | |
.then(val => { | |
console.log(val); | |
}) | |
.catch(console.error) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment