Future<T>.sync constructor

Future<T>.sync(
  1. FutureOr<T> computation()
)

The result of calling computation as a future.

Mainly used when working with functions returning a FutureOr<T>, or non-async functions in a non-async asynchronous function, where you want to capture any error in a future.

If calling computation throws, the returned future is completed with the error.

If calling computation returns a Future<T>, that future is returned.

If calling computation returns a non-Future<T> value, a future is created which has been completed with that value.

Example:

Future<int> asyncAdd(
  FutureOr<int> Function() a,
  FutureOr<int> Function() b,
) =>
  (Future.sync(a), Future.sync(b)).wait.then((ab) => ab.$1 + ab.$2);

To create a future with a known value, use Future.syncValue instead, as Future.syncValue(12).

Implementation

factory Future.sync(FutureOr<T> computation()) {
  FutureOr<T> result;
  try {
    result = computation();
  } catch (error, stackTrace) {
    return _Future<T>()
      .._asyncCompleteErrorObject(_interceptCaughtError(error, stackTrace));
  }
  return result is Future<T> ? result : _Future<T>.value(result);
}