Should Asynchronous function calls be cancelled before wait if error occurs in Ballerina?

34 Views Asked by At

Regarding Asynchronous function calls https://ballerina.io/learn/by-example/asynchronous-function-calls/

Should we call future.cancel() if the code between the future declaration and wait throws an error or returns? Example:

future<int> fut = start foo();
// Code fails or returns here
 int|error x = wait fut; 
1

There are 1 best solutions below

0
On

I would say it depends on the logic (e.g., whether the strand yields, whether this is called from a main function, etc.). Note that future:cancel requests cancellation (rather than immediate termination of the strand).

This sets the cancellation flag in the strand corresponding to f. Each time that a strand yields, it will check the cancellation flag and terminate abnormally if the flag is set.

https://lib.ballerina.io/ballerina/lang.future/0.0.0#cancel