Skip to content

Instantly share code, notes, and snippets.

@kamichidu
Created June 28, 2016 05:11
Show Gist options
  • Save kamichidu/a714d59d643c3c65ac4401c8f7e4e87a to your computer and use it in GitHub Desktop.
Save kamichidu/a714d59d643c3c65ac4401c8f7e4e87a to your computer and use it in GitHub Desktop.
js-executor
module.exports= (function(){
'use strict';
var Executor= function(opts){
opts || (opts= {});
this.nactives= opts.nactives || 10;
this.actives= [];
this.all= [];
};
Executor.prototype.submit= function(fun, ctx){
var that= this;
var waiter= function(resolve, reject){
if(that.actives.length >= that.nactives)
{
console.log(' Wait next time. (actives = ' + that.actives.length + ')');
return setTimeout(function(){
waiter.call(that, resolve, reject);
}, 0);
}
console.log(' execute (actives = ' + that.actives.length + ')');
that.actives.push(true);
fun.call(ctx, resolve, reject);
};
var popper= function(){
that.actives.pop();
}
var promise= new Promise(waiter);
promise.then(popper, popper);
this.all.push(promise);
return promise;
};
Executor.prototype.wait= function(){
return Promise.all(this.all);
};
return Executor;
})();
(function(){
'use strict';
var Executor= require('./executor.js');
var executor= new Executor({
nactives: 4
});
for(var i= 0; i < 20; ++i)
{
console.log('submitting');
executor.submit(function(resolve, reject){
var fs= require('fs');
fs.readFile('./executor.js', function(){
resolve();
console.log(' done');
});
});
}
console.log('waiting');
executor
.wait()
.then(function(){
console.log('all done');
})
.catch(function(e){
console.log('Something wrong', e);
})
;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment