Reputation: 1176
I have series of promise chains, which took sufficient time to get completed. Below is the sample chain setup:
myJob1()
.then(myJob2)
.then(myJob3)
.then(myJob4)
.then(myJob5)
.then(myJob6)
.catch(myJobError);
In mean time when this job is running, if the person on UI think to cancel it, How can it be cancelled in whatever stage/function execution it is?
What can be the possible solution?
Upvotes: 4
Views: 5700
Reputation: 19301
One alternative to modifying code for multiple job functions might be to check a user cancelled flag between jobs. If the granularity of this kind of checking is not too course, then you could asynchronously set a (somewhat) global cancelled flag and proceed along the lines of:
let userCancelled = false;
let checkCancel = function( data) {
if( userCancelled)
throw new Error( "cancelled by user"); // invoke catch handling
return data; // pass through the data
}
myJob1()
.then(myJob2).then( checkCancel)
.then(myJob3).then( checkCancel)
.then(myJob4).then( checkCancel)
.then(myJob5).then( checkCancel)
.then(myJob6).then( checkCancel)
.catch(myJobError);
Don't forget that if you do check the cancelled flag inside a job, all you need to do is throw an error to have it bubble down the promise chain.
Upvotes: 4
Reputation: 2047
There is no way to cancel the promise (remember each of thens is returning a new promise) or clear the then
callback.
Probably you are looking for something like redux-observable
, where you can specify clause, until promise execution is actual.
See more in details: https://github.com/redux-observable/redux-observable/blob/master/docs/recipes/Cancellation.md
As alternative I may only suggest you to create and manage some flag which determines whether further process is needed or not:
// Inside each of promises in chain
if (notCancelled) {
callAjax(params).then(resolve);
}
Or reject:
// Inside each of promises in chain
if (cancelled) {
// Will stop execution of promise chain
return reject(new Error('Cancelled by user'));
}
Upvotes: 1