promiseToFuture<T> function Null safety

Future<T> promiseToFuture<T>(
  1. Object jsPromise
)

Converts a JavaScript Promise to a Dart Future.

@JS()
external Promise<num> get threePromise; // Resolves to 3

final Future<num> threeFuture = promiseToFuture(threePromise);

final three = await threeFuture; // == 3

Implementation

Future<T> promiseToFuture<T>(Object jsPromise) {
  final completer = Completer<T>();

  final success = convertDartClosureToJS((r) => completer.complete(r), 1);
  final error = convertDartClosureToJS((e) {
    // Note that `completeError` expects a non-nullable error regardless of
    // whether null-safety is enabled, so a `NullRejectionException` is always
    // provided if the error is `null` or `undefined`.
    if (e == null) {
      return completer.completeError(
          NullRejectionException._(JS('bool', '# === undefined', e)));
    }
    return completer.completeError(e);
  }, 1);

  JS('', '#.then(#, #)', jsPromise, success, error);
  return completer.future;
}