function QueueLoadFile(deals) {
var _self = this,
defer = $.Deferred();
var _queueList = [],
_queueLen = 0,
_isDoing = false;
function push(deals) {
var _self = this,
beginIndex = _queueLen;
if(!deals) {
return ;
}
if(deals instanceof Array) {
for(var i= 0, len=deals.length; i<len; ++i) {
_push(deals[i]);
}
} else {
_push(deals);
}
return beginIndex;
}
function _push(deal) {
_queueList.push({
id: deal.id,
data: deal.data,
action: typeof deal.action === 'function' ? deal.action : normal,
status: 'ready',
result: ''
});
_queueLen ++;
_isDoing && _doing(_queueList.length-1);
}
function _doing(index) {
if(!_queueList[index]) {
_queueLen--;
}
if(_queueLen==0) {
defer.resolve();
}
if(_queueList[index].status != 'finished' && _queueList[index].status != 'wrong'){
_queueList[index].action.call(_self, _queueList[index].data).done(function(data){
_queueList[index].result = data;
_queueList[index].status = 'finished';
_queueLen --;
console.log( '[ EVENT ] ' + (_queueList[index].id || index) + ':: ' + ('finished...') );
(_queueLen==0) && defer.resolve(_queueList);
}).fail(function(){
_queueList[index].status = 'wrong';
defer.reject(_queueList[index]);
});
}
_queueList[index].status = 'doing';
}
function begain() {
var _self = this;
if(!_self._isDoing) {
for(var len=_queueLen-1; len>=0; --len) {
_doing(len);
}
}
return defer.promise();
}
function normal() {
var def = $.Deferred();
def.resolve('');
return def.promise();
}
push(deals);
// exports
_self.begain = begain;
_self.push = push;
}