Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // this is simple 1 file 1 route,
- // app with cancellation of promise with bluebird library
- //
- // canellation of promise which have interval also stopping interval with onCancel
- const express = require('express');
- const app = express();
- const path = require('path');
- const bodyParser = require('body-parser');
- const Promise = require('bluebird');
- Promise.config({
- warnings: true,
- longStackTraces: true,
- cancellation: true,
- monitoring: true
- });
- app.use(bodyParser.json());
- app.use(express.static(path.join(__dirname, 'public')));
- const forFoo = (loopIndex) => {
- return new Promise((resolve, reject) => {
- setTimeout(() => {
- console.log('in loop, index ', loopIndex);
- resolve();
- }, 100)
- });
- };
- //promise
- const foo = () => {
- return new Promise((resolve, reject, onCancel) => {
- let index = 0;
- const intervalId = setInterval(async() => {
- let loopIndex = 2;
- index++;
- console.log('in interval, index: ', index);
- //actuall interval task
- while(loopIndex > 0) {
- await forFoo(loopIndex);
- loopIndex--;
- }
- if(index === 5) {
- clearInterval(intervalId);
- resolve();
- }
- }, 1000);
- onCancel(() => {
- clearInterval(intervalId);
- });
- });
- };
- //test route here
- app.get('/test', async(req, res) => {
- let searchPromise = foo()
- .then(function() {
- console.log('not cancel')
- })
- .catch(function(e) {
- console.log(e);
- })
- .finally(function() {
- // This check is necessary because `.finally` handlers are always called.
- if (!searchPromise.isCancelled()) {
- //hideSpinner();
- console.log('not canceled')
- }
- });
- setTimeout(() => {
- searchPromise.cancel();
- }, 3000);
- res.send('Completed');
- });
- app.listen(5000, () => {
- console.log('Serwer nasłuchuje na porcie: ', 5000)
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement