async<S, F extends Object> static method

Future<Result<S, F>> async<S, F extends Object>(
  1. _AsyncResultEarlyReturnFunction<S, F> fn
)

Creates a async context for early return, similar to "Do notation". Here "$" is used as the "Early Return Key". when "$" is used on a type Err, immediately the context that "$" belongs to is returned with that Err. Works like the Rust "?" operator, which is a "Early Return Operator". e.g.

    FutureResult<int,String> innerFn() async => Err("message");

    FutureResult<int, String> innerFn2() async => Ok(1);

    FutureResult<int, String> earlyReturn() => Result.early(($) async {
        int y = 2;
        int x = await innerFn()[$]; // returns [Err] here immediately
        int z = await innerFn2()[$]; // innerFn2 will not be executed
        return Ok(x + y + z);
      });
    }
    expect(await earlyReturn().unwrapErr(), "message");

This should be used at the top level of a function as above. Passing "$" to any other functions, nesting, or attempting to bring "$" out of the original scope should be avoided.

Implementation

@pragma("vm:prefer-inline")
static Future<Result<S, F>> async<S, F extends Object>(
  // ignore: library_private_types_in_public_api
  _AsyncResultEarlyReturnFunction<S, F> fn,
) async {
  try {
    return await fn(_ResultEarlyReturnKey._());
  } on _ResultEarlyReturnNotification<F> catch (notification) {
    return notification.value;
  }
}