Blog

SimplePromise – A simple javascript promise with approve, reject, cancel & progress features

Needed a cancelable promise for my project. Also, needed to solve multiple resolve & reject problem done by original Promise because I was making a lot of asynchronous requests and gathering all data together.

Here is SimplePromise which works same as normal promise and does exactly what I needed, hope it helps someone.

// SimplePromise
// Promise with cancel feature and also solves multiple resolve & reject problem in original Promise.
// Adds progress feature too
// Does not need original Promise to function
var SimplePromise = function(func) {
var promise = this;
this.then = function(func) {
promise.resolve = func;
return promise;
};
this.catch = function(func) {
promise.reject = func;
return promise;
};

this.cancel = function(bool) {
if (typeof bool === "undefined") bool = true;
promise.canceled = bool;
return promise;
};
this.progress = function(func) {
promise._progress = func;
return promise;
};
setTimeout(function() {
func(function() {
if (promise.canceled !== true && typeof promise.resolve !== "undefined" && typeof promise.done === "undefined") { promise.resolve.apply(null, arguments); promise.done = true; }
}, function() {
if (promise.canceled !== true && typeof promise.reject !== "undefined" && typeof promise.done === "undefined") { promise.reject.apply(null, arguments); promise.done = true; }
}, function() {
if (promise.canceled !== true && typeof promise._progress !== "undefined") promise._progress.apply(null, arguments);
});
}, 1);
};

// Test new Promise with cancel & multiple resolve, reject & progress
var promise = new SimplePromise(function(resolve, reject, progress) {
progress(10, 100);
progress (30, 100);
resolve("resolve");
resolve("resolve");
reject("reject");
reject("reject");
}).progress(function(value, total) {
console.log(((value / total) * 100) + "%");
}).then(function(value) {
console.log(value);
}).catch(function(value) {
console.log(value);
}).cancel(true); // Remove cancel to test resolve, reject & progress

Leave a Reply

Your email address will not be published. Required fields are marked *