Guest User

Untitled

a guest
Dec 13th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. const PQ = require('p-q');
  2.  
  3. // so many parallel promises should run at the same time
  4. const concurrency = 3;
  5.  
  6. // simulate work with delay function
  7. function delay(times, ms = 1000) {
  8. return new Promise((resolve) => {
  9. setTimeout(resolve, times * ms);
  10. });
  11. }
  12.  
  13. // somewhat official function for returning random integer in range
  14. function getRandomInt(min, max) {
  15. min = Math.ceil(min);
  16. max = Math.floor(max);
  17. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  18. }
  19.  
  20. // initialize local queue - set pre-defined function, that returns a promise
  21. const queue = new PQ(async(data) => {
  22. await delay(getRandomInt(0, 5));
  23. console.log(`finished ${data.i}`);
  24. });
  25.  
  26. // the heart of the operation
  27. // add one item to queue and block until one finishes,
  28. // so there is no more than 3 running
  29. async function add(data) {
  30. console.log(`add ${data.i}`);
  31. queue.add(data);
  32. if (queue.length() >= concurrency) {
  33. await new Promise(resolve => {
  34. queue.once('processed', () => {
  35. resolve();
  36. });
  37. });
  38. }
  39. }
  40.  
  41. async function main() {
  42. // let's simulate rabbitmq - should not accept more than 3 items at a time,
  43. // so that other instances can fetch new events
  44. for (let i = 0; i < 100; i++) {
  45. if (i < 10) {
  46. await add({i});
  47. } else if (i > 30 && i < 40) {
  48. await add({i});
  49. } else {
  50. await delay(1);
  51. }
  52. }
  53. }
  54.  
  55. main()
  56. .then(() => {
  57. console.log('END');
  58. })
  59. .catch(err => {
  60. throw err;
  61. });
Add Comment
Please, Sign In to add comment