I’d like to have my public function return in a timely manner and continue some stuff in a new task() / thread
how do I do this?
I’d like to have my public function return in a timely manner and continue some stuff in a new task() / thread
how do I do this?
That’s what async blocks provide. Toy example:
actor a {
var counter : Nat = 0;
public func add() : async Nat {
ignore async {
counter := counter + 1;
};
return counter;
};
}
Intuitively, the async keyword requests an expression to be executed asynchronously, i.e., later. If you ignore its result instead of awaiting it, then you’ll proceed before it’s performed.
Of course, you can also move the async block into a helper function, which perhaps looks more familiar:
actor a {
var counter : Nat = 0;
public func add() : async Nat {
ignore task();
return counter;
};
func task() : async () {
counter := counter + 1;
};
}
But be aware that other messages might arrive before the async block is executed. If it was important that the task is executed before any other message, then you’d need to do some extra synchronisation manually. I would recommend against such a pattern, however. Only use async when the order of execution relative to other ingress messages doesn’t matter.
Thank you so much!
Really awesome explanation and examples.
Will try my best to be responsible with this powerful functionality.