Deffered
Simple "deffered" implementation example
by winns
JavaScript
var Deffered = function() {
this.id = Math.random().toString(36).substr(2, 9);
this.onResolve = function() {};
this.onFail = function() {};
this.resolve = function() {
this.onResolve( this.id );
};
this.fail = function() {
this.onFail();
};
};
var when = function( arr, success, error ) {
this.onResolve = function( id ) {
for (var i=0; i < arr.length; i++) {
if (arr[i].id === id) {
arr.splice(i, 1);
break;
}
}
if (! arr.length) success();
};
for (var i=0; i < arr.length; i++) {
arr[i].onResolve = this.onResolve;
arr[i].onFail = error;
}
};
var d1 = new Deffered();
var d2 = new Deffered();
var d3 = new Deffered();
setTimeout(function() {
d1.resolve();
}, 1000);
setTimeout(function() {
d2.resolve();
}, 4000);
setTimeout(function() {
d3.resolve();
}, 1000);
when(
[ d1, d2, d3 ],
function() {
console.log( 'success' );
},
function() {
console.log( 'error' );
}
);