I would like to have a cancelable promise that reports progress at the same time. Something like a combination of p-progress and p-cancelable. And while usage of any of them separately is simple I'm struggling a bit to combine them both.
This is what I tried so far which successfully reports progress but throws cancelablePromise.cancel is not a function error.
import PCancelable from 'p-cancelable';
import PProgress from 'p-progress';
const cancelablePromise = doJobWithProgress();
try {
cancelablePromise.onProgress((progress) => {
console.log('progress: ' + progress);
});
await sleep(500);
cancelablePromise.cancel();
const result = await cancelablePromise;
console.log("result", result);
}
catch (error) {
console.log("Main catch error: " + error);
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function doJobWithProgress() {
return PProgress((progressCallback) => {
return new PCancelable((resolve, reject, onCancel) => {
try {
let progress = 0;
const interval = setInterval(() => {
progress += 0.1;
progressCallback(progress);
}, 100);
const timeout = setTimeout(() => {
const result = 1;
clearTimeout(timeout);
clearInterval(interval);
resolve(result);
}, 1000);
onCancel(() => {
console.log('canceled');
clearTimeout(timeout);
clearInterval(interval);
});
}
catch (error) {
console.log('Promise catch error: ' + error);
reject(error);
}
});
});
}