Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created January 27, 2017 16:25
Show Gist options
  • Save dengjonathan/de7f8976ce1c24924e3ab069d5d5feaf to your computer and use it in GitHub Desktop.
Save dengjonathan/de7f8976ce1c24924e3ab069d5d5feaf to your computer and use it in GitHub Desktop.
Naive Promise implementation
// 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