Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. // async.eachLimit:
  2. import { eachLimit } from 'async';
  3. import sleep from './sleep';
  4.  
  5. let times = [100, 150, 200, 250, 300];
  6.  
  7. console.log('sleep start');
  8. console.time('async with concurrency');
  9. eachLimit(times, 2, sleep, (err) => {
  10. console.timeEnd('async with concurrency');
  11. console.log('sleep complete');
  12. });
  13.  
  14. // Promise.map
  15. import Promise from 'bluebird';
  16. import sleep from './sleep';
  17.  
  18. let times = [100, 150, 200, 250, 300];
  19.  
  20. console.log('sleep start');
  21. console.time('promise one by one');
  22. Promise.map(times, (time) => {
  23. return sleep(time);
  24. }, {
  25. concurrency: 2
  26. }).then(() => {
  27. console.timeEnd('promise one by one');
  28. console.log('sleep complete');
  29. });
  30.  
  31. // ES7 async/await:
  32. import sleep from './sleep';
  33.  
  34. let times = [100, 150, 200, 250, 300];
  35.  
  36. (async function() {
  37. console.log('sleep start');
  38. console.time('es7 with concurrency');
  39. await pool(2, async () => {
  40. await sleep(times.shift());
  41. return times.length > 0;
  42. });
  43. console.timeEnd('es7 with concurrency');
  44. console.log('sleep complete');
  45. }());
  46.  
  47. async function pool(size, task) {
  48. var active = 0;
  49. var done = false;
  50. var errors = [];
  51. return new Promise((resolve, reject) => {
  52. next();
  53. function next() {
  54. while (active < size && !done) {
  55. active += 1;
  56. task()
  57. .then(more => {
  58. if (--active === 0 && (done || !more))
  59. errors.length === 0 ? resolve() : reject(errors);
  60. else if (more)
  61. next();
  62. else
  63. done = true;
  64. })
  65. .catch(err => {
  66. errors.push(err);
  67. done = true;
  68. if (--active === 0)
  69. reject(errors);
  70. });
  71. }
  72. }
  73. });
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement