Skip to content

FutureOfJSAnyToJSPromise<T extends JSAny?>

extension FutureOfJSAnyToJSPromise<T extends JSAny?> on Future<T>

Conversions from Future to JSPromise where the Future returns a value.

Properties

toJS extension no setter

JSPromise<T> get toJS

A JSPromise that either resolves with the result of the completed Future or rejects with an object that contains its error.

The rejected object contains the original error as a JSBoxedDartObject in the property error and the original stack trace as a String in the property stack.

Available on Future<T>, provided by the FutureOfJSAnyToJSPromise<T extends JSAny?> extension

Implementation
dart
JSPromise<T> get toJS {
  return JSPromise<T>(
    (JSFunction resolve, JSFunction reject) {
      this.then(
        (JSAny? value) {
          resolve.callAsFunction(resolve, value);
          return value;
        },
        onError: (Object error, StackTrace stackTrace) {
          &#47;&#47; TODO(srujzs): Can we do something better here? This is pretty much
          &#47;&#47; useless to the user unless they call a Dart callback that consumes
          &#47;&#47; this value and unboxes.
          final errorConstructor = globalContext['Error'] as JSFunction;
          final wrapper = errorConstructor.callAsConstructor<JSObject>(
            "Dart exception thrown from converted Future. Use the properties "
                    "'error' to fetch the boxed error and 'stack' to recover "
                    "the stack trace."
                .toJS,
          );
          wrapper['error'] = error.toJSBox;
          wrapper['stack'] = stackTrace.toString().toJS;
          reject.callAsFunction(reject, wrapper);
          return wrapper;
        },
      );
    }.toJS,
  );
}