Skip to content

Instantly share code, notes, and snippets.

@d0peCode
Created June 4, 2019 16:14
Show Gist options
  • Save d0peCode/f8bc114c5bef248493c037d06ad3b476 to your computer and use it in GitHub Desktop.
Save d0peCode/f8bc114c5bef248493c037d06ad3b476 to your computer and use it in GitHub Desktop.
// #bluebird, #bluebird-retry, #bluebird-cancellation, #eventBus
const Promise = require('bluebird');
const retry = require('bluebird-retry');
const eventBus = require('js-event-bus')();
Promise.config({warnings: true, longStackTraces: true, cancellation: true, monitoring: true});
//promise child function
const child = () => {
return new Promise((resolve, reject, onCancel) => {
console.log('CALLED CHILD');
reject(new Error('Rejected from child'));
onCancel(() => {
console.log('Registered cancel in child function');
});
});
};
//promise parent function
const parent = () => {
return new Promise((resolve, reject, onCancel) => {
setTimeout(async() => {
console.log('CALLED PARENT');
try {
await retry(child, { max_tries: 4, interval: 500 })
} catch (e) {
reject(new Error('Rejected from parent function'));
}
},100);
onCancel(() => {
console.log('Registered cancel in parent function');
retry.StopError(new Error('Stop retrying child'));
reject(new Error('Cancelled parent'));
});
});
};
//background manager - should be able to stop promise chain
const backgroundProcess = () => {
let index = 0;
const intervalId = setInterval(() => {
index++;
if(index === 3) {
console.warn('Emit stop::all event');
eventBus.emit('stop::all');
clearInterval(intervalId);
}
}, 500);
};
//another promise
const continueStack = () => {
return new Promise((resolve, reject) => {
console.log('started continueStack');
setTimeout(() => {
console.log('finished continueStack');
resolve();
}, 2000);
});
};
//test route here
async function start() {
backgroundProcess(); //fire stop:all event after 2 sec
let promise;
eventBus.on('stop::all', () => {
if(promise && promise.cancel) {
console.warn('Caught stop::all event');
promise.cancel();
} else {
console.log('somehow promise was not properly set at this point');
}
});
try {
promise = parent();
await promise; // so continueStack is not called until parent resolves, I guess this is your desire
console.log('after parent promise');
await continueStack();
} catch (e) {
console.log('Caught error in endpoint');
}
};
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment