Skip to content

Instantly share code, notes, and snippets.

@surajhell88
Last active May 19, 2018 09:07
Show Gist options
  • Save surajhell88/350e928ba3abd352d43e3cfb8441877c to your computer and use it in GitHub Desktop.
Save surajhell88/350e928ba3abd352d43e3cfb8441877c to your computer and use it in GitHub Desktop.
Simple Promise Implementation

Simple Promise Implementation

A simple javascript implmentation of promise object. It isn't the best solution but does solve the given problem statement. The probable todo items/improvements would be to refer MDN doc for Promise

Listing a few here:

  1. .all(iterable)
  2. .reject(promiseInstance)
  3. .resolve(promiseInstance)
  4. .finally(callback)
function MyPromise(callback) {
var queue = [];
var catchMe;
var resolve = function(value) {
let lastVal = value;
queue.forEach((next) => {
lastVal = next(lastVal);
});
};
var reject = function(error) {
catchMe(error);
};
callback(resolve, reject);
return {
then: function(cb) {
if (typeof cb === 'function') queue.push(cb);
return this;
},
catch: function(cb) {
catchMe = cb;
},
};
}
var aPromise = new MyPromise(function(resolve, reject) {
setTimeout(function() {
resolve('Accepted');
// reject('Error');
}, 1000);
})
.then(function(value) { console.log(value); return value; }) // ‘Accepted’
.then(function(value) { console.log(value) }) // ‘Accepted’
.catch(function(error) { console.log(error) }); // ‘Error’
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment