Very useful thing (missed in initial version):
args = Array.prototype.slice.call(arguments, 0);
This line of code magically converts magically converts arguments
from object into array
Very useful thing (missed in initial version):
args = Array.prototype.slice.call(arguments, 0);
This line of code magically converts arguments
from object into array
Very useful thing (missed in initial version):
args = Array.prototype.slice.call(arguments, 0);
This line of code magically converts arguments
from object into array
I've added always
handler. Now the code looks like this (thanx to Flambino)
function defer() {
var currentState = 'pending',
callbacks = { resolved: [], rejected: [], always: [] },
args = []; //
function execute(state) {
var cb;
while(callbacks[state].length) {
cb = callbacks[state].shift();
if( typeof cb === 'function' ) cb.apply(this, args);
}
}
// generic function factory for done/fail functions
function handle(state) {
return function (cb) {
callbacks[state].push(cb);
if(currentState !== 'pending') {
if(currentState === state) execute(state);
if(state === 'always') execute('always');
}
}
}
// generic function factory for resolve/reject functions
function complete(state) {
return function () {
if(currentState !== 'pending') return;
args = Array.prototype.slice.call(arguments, 0);
currentState = state;
execute(state);
execute('always');
}
}
return {
promise: function () {
return {
done: handle('resolved'),
fail: handle('rejected'),
always: handle('always')
};
},
resolve: complete('resolved'),
reject: complete('rejected')
};
}
Very useful thing (missed in initial version):
args = Array.prototype.slice.call(arguments, 0);
This line of code magically converts arguments
from object into array