Continuing computation after returning

Is it possible for an actor to continue computation after returning from an update method, for example to optimize data structures after something has been calculated? In other words I’m asking if it is possible to return a value early before the function is done executing.

No, that’s not directly possible in Motoko at the moment. You can however approximate it by having the actor invoke another oneway method on itself before returning:

var x : Nat = 0;
public func f(n : Nat) : async Nat {
  let old = x;
  x := n;
  cleanup();  // note: no await
  return old;

shared func cleanup() {
  // do something here

The thing to be aware of, though, is that cleanup will not be executed atomically with f, and other methods might execute in the mean time.