Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // async.eachLimit:
- import { eachLimit } from 'async';
- import sleep from './sleep';
- let times = [100, 150, 200, 250, 300];
- console.log('sleep start');
- console.time('async with concurrency');
- eachLimit(times, 2, sleep, (err) => {
- console.timeEnd('async with concurrency');
- console.log('sleep complete');
- });
- // Promise.map
- import Promise from 'bluebird';
- import sleep from './sleep';
- let times = [100, 150, 200, 250, 300];
- console.log('sleep start');
- console.time('promise one by one');
- Promise.map(times, (time) => {
- return sleep(time);
- }, {
- concurrency: 2
- }).then(() => {
- console.timeEnd('promise one by one');
- console.log('sleep complete');
- });
- // ES7 async/await:
- import sleep from './sleep';
- let times = [100, 150, 200, 250, 300];
- (async function() {
- console.log('sleep start');
- console.time('es7 with concurrency');
- await pool(2, async () => {
- await sleep(times.shift());
- return times.length > 0;
- });
- console.timeEnd('es7 with concurrency');
- console.log('sleep complete');
- }());
- async function pool(size, task) {
- var active = 0;
- var done = false;
- var errors = [];
- return new Promise((resolve, reject) => {
- next();
- function next() {
- while (active < size && !done) {
- active += 1;
- task()
- .then(more => {
- if (--active === 0 && (done || !more))
- errors.length === 0 ? resolve() : reject(errors);
- else if (more)
- next();
- else
- done = true;
- })
- .catch(err => {
- errors.push(err);
- done = true;
- if (--active === 0)
- reject(errors);
- });
- }
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement