Given this pattern
someArray.reduce(function(p, item) {
return p.then(function() {
return someFunction(item);
});
}, $.Deferred().resolve()).then(fun
One solution possible :
var $j = function(val, space) {
return JSON.stringify(val, null, space || '')
}
var log = function(val) {
document.body.insertAdjacentHTML('beforeend', '' + val + '
')
}
var async = function(cur){
var pro = new Promise(function(resolve, reject) {
log('loading : ' + cur.name);
// we simualate the loading
setTimeout(function() {
if(cur.name === 'file_3.js'){
reject(cur.name);
}
resolve(cur.name);
}, 1 * 1000);
});
return pro;
}
var files = '12345'.split('').map(function(v) {
return {
name: 'file_' + v + '.js',
}
});
var listed = files.reduce(function(t,v){
t.p = t.p.then( function(){
return async( v )
.then(function(rep){
t.fulfilled.push(rep);
log('fulfilled :' + rep);
return rep;
} , function(rep){
t.rejected.push(rep);
log('-----| rejected :' + rep);
return rep;
}
).then(function(val){ t.treated.push(val) })
});
return t;
} , {p : Promise.resolve() , treated : [] , fulfilled : [] , rejected : [] } )
listed.p.then( function(){
log( 'listed : ' + $j( listed , ' ' ))
});