-
Notifications
You must be signed in to change notification settings - Fork 2
Atomic sub chains
DigitalBrainJS edited this page Oct 17, 2021
·
1 revision
Sometimes you need to prevent any sub-chain from being canceled from the outside because you want to allow some
already started asynchronous procedure to be completed before closing the following promise chains.
To solve this challenge use .atomic(["disabled"|"detached"|"await"])
method.
-
'detached'
- keep the sub-chain execution running in 'background', the main chain reject immediately -
'await'
- wait for the sub-chain to complete and then reject the next promise in the outer chain -
false
considering as'disabled'
-
true
considering as'await'
Check out the difference with examples:
Normal cancellation behaviour .atomic('disabled')
(Demo):
const p = CPromise.delay(1000, 1)
.then((v) => {
console.log("p1");
return CPromise.delay(1000, 2);
})
.then((v) => {
console.log("p2");
return CPromise.delay(1000, 3);
})
.atomic()
.then((v) => {
console.log("p3");
return CPromise.delay(1000, 4);
})
.then(
(value) => console.log(`Done:`, value),
(err) => console.warn(`Fail: ${err}`)
);
setTimeout(() => p.cancel(), 1500);
output:
p1
Fail: CanceledError: canceled
Process finished with exit code 0
.atomic('detached')
cancellation behaviour (Demo):
const p = CPromise.delay(1000, 1)
.then((v) => {
console.log("p1");
return CPromise.delay(1000, 2);
})
.then((v) => {
console.log("p2");
return CPromise.delay(1000, 3);
})
.atomic('detached')
.then((v) => {
console.log("p3");
return CPromise.delay(1000, 4);
})
.then(
(value) => console.log(`Done:`, value),
(err) => console.warn(`Fail: ${err}`)
);
setTimeout(() => p.cancel(), 1500);
output:
p1
Fail: CanceledError: canceled
p2
.atomic('await')
cancellation behaviour (Demo):
const p = CPromise.delay(1000, 1)
.then((v) => {
console.log("p1");
return CPromise.delay(1000, 2);
})
.then((v) => {
console.log("p2");
return CPromise.delay(1000, 3);
})
.atomic()
.then((v) => {
console.log("p3");
return CPromise.delay(1000, 4);
})
.then(
(value) => console.log(`Done:`, value),
(err) => console.warn(`Fail: ${err}`)
);
setTimeout(() => p.cancel(), 1500);
output:
p1
p2
Fail: CanceledError: canceled
Process finished with exit code 0