Last active
January 27, 2017 16:43
-
-
Save dengjonathan/85e43fc0c7f6385737230f4a07cdf08b to your computer and use it in GitHub Desktop.
Naive Promise
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: errHandler => { | |
_catch = errHandler | |
return promise; | |
} | |
} | |
const fulfill = data => { | |
while (_thens.length) { | |
try { | |
data = _thens.shift()(data); | |
} catch (err) { | |
_catch && _catch(err); | |
break; | |
} | |
} | |
}; | |
const reject = err => { | |
_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