Advertisement
Guest User

Untitled

a guest
Jun 15th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. // #bluebird, #bluebird-retry, #bluebird-cancellation, #eventBus
  2. const Promise = require('bluebird');
  3. const retry = require('bluebird-retry');
  4. const eventBus = require('js-event-bus')();
  5.  
  6. Promise.config({warnings: true, longStackTraces: true, cancellation: true, monitoring: true});
  7.  
  8. //promise child function
  9. const child = () => {
  10. return new Promise((resolve, reject, onCancel) => {
  11. console.log('CALLED CHILD');
  12. reject(new Error('Rejected from child'));
  13.  
  14. onCancel(() => {
  15. console.log('Registered cancel in child function');
  16. });
  17. });
  18. };
  19.  
  20. //promise parent function
  21. const parent = () => {
  22. return new Promise((resolve, reject, onCancel) => {
  23. setTimeout(async() => {
  24. console.log('CALLED PARENT');
  25. try {
  26. await retry(child, { max_tries: 4, interval: 500 })
  27. } catch (e) {
  28. reject(new Error('Rejected from parent function'));
  29. }
  30. },100);
  31.  
  32. onCancel(() => {
  33. console.log('Registered cancel in parent function');
  34. retry.StopError(new Error('Stop retrying child'));
  35. reject(new Error('Cancelled parent'));
  36. });
  37. });
  38. };
  39.  
  40. //background manager - should be able to stop promise chain
  41. const backgroundProcess = () => {
  42. let index = 0;
  43. const intervalId = setInterval(() => {
  44. index++;
  45. if(index === 3) {
  46. console.warn('Emit stop::all event');
  47. eventBus.emit('stop::all');
  48. clearInterval(intervalId);
  49. }
  50. }, 500);
  51. };
  52.  
  53. //another promise
  54. const continueStack = () => {
  55. return new Promise((resolve, reject) => {
  56. console.log('started continueStack');
  57. setTimeout(() => {
  58. console.log('finished continueStack');
  59. resolve();
  60. }, 2000);
  61. });
  62. };
  63.  
  64. //test route here
  65. async function start() {
  66. backgroundProcess(); //fire stop:all event after 2 sec
  67.  
  68. let promise;
  69.  
  70. eventBus.on('stop::all', () => {
  71. if(promise && promise.cancel) {
  72. console.warn('Caught stop::all event');
  73. promise.cancel();
  74. } else {
  75. console.log('somehow promise was not properly set at this point');
  76. }
  77. });
  78.  
  79. try {
  80. promise = parent();
  81. await promise; // so continueStack is not called until parent resolves, I guess this is your desire
  82. console.log('after parent promise');
  83. await continueStack();
  84. } catch (e) {
  85. console.log('Caught error in endpoint');
  86. }
  87. };
  88.  
  89. start();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement