Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Last active January 27, 2017 16:43
Show Gist options
  • Save dengjonathan/85e43fc0c7f6385737230f4a07cdf08b to your computer and use it in GitHub Desktop.
Save dengjonathan/85e43fc0c7f6385737230f4a07cdf08b to your computer and use it in GitHub Desktop.
Naive Promise
// 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