Skip to content

Instantly share code, notes, and snippets.

@d0peCode
Created May 11, 2019 17:21
Show Gist options
  • Save d0peCode/b054fec7e0ac619ed1f8935d19cf7b87 to your computer and use it in GitHub Desktop.
Save d0peCode/b054fec7e0ac619ed1f8935d19cf7b87 to your computer and use it in GitHub Desktop.
// 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)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment