Created
June 28, 2016 05:11
-
-
Save kamichidu/a714d59d643c3c65ac4401c8f7e4e87a to your computer and use it in GitHub Desktop.
js-executor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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