Advertisement
Guest User

Untitled

a guest
May 21st, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. // this is simple 1 file 1 route,
  2. // app with cancellation of promise with bluebird library
  3. //
  4. // canellation of promise which have interval also stopping interval with onCancel
  5.  
  6. const express = require('express');
  7. const app = express();
  8. const path = require('path');
  9. const bodyParser = require('body-parser');
  10. const Promise = require('bluebird');
  11.  
  12. Promise.config({
  13. warnings: true,
  14. longStackTraces: true,
  15. cancellation: true,
  16. monitoring: true
  17. });
  18.  
  19. app.use(bodyParser.json());
  20. app.use(express.static(path.join(__dirname, 'public')));
  21.  
  22. const forFoo = (loopIndex) => {
  23. return new Promise((resolve, reject) => {
  24. setTimeout(() => {
  25. console.log('in loop, index ', loopIndex);
  26. resolve();
  27. }, 100)
  28. });
  29. };
  30.  
  31. //promise
  32. const foo = () => {
  33. return new Promise((resolve, reject, onCancel) => {
  34. let index = 0;
  35. const intervalId = setInterval(async() => {
  36. let loopIndex = 2;
  37. index++;
  38. console.log('in interval, index: ', index);
  39.  
  40. //actuall interval task
  41. while(loopIndex > 0) {
  42. await forFoo(loopIndex);
  43. loopIndex--;
  44. }
  45.  
  46. if(index === 5) {
  47. clearInterval(intervalId);
  48. resolve();
  49. }
  50. }, 1000);
  51. onCancel(() => {
  52. clearInterval(intervalId);
  53. });
  54. });
  55. };
  56.  
  57. //test route here
  58. app.get('/test', async(req, res) => {
  59. let searchPromise = foo()
  60. .then(function() {
  61. console.log('not cancel')
  62. })
  63. .catch(function(e) {
  64. console.log(e);
  65. })
  66. .finally(function() {
  67. // This check is necessary because `.finally` handlers are always called.
  68. if (!searchPromise.isCancelled()) {
  69. //hideSpinner();
  70. console.log('not canceled')
  71. }
  72. });
  73.  
  74. setTimeout(() => {
  75. searchPromise.cancel();
  76. }, 3000);
  77. res.send('Completed');
  78. });
  79.  
  80. app.listen(5000, () => {
  81. console.log('Serwer nasłuchuje na porcie: ', 5000)
  82. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement