runJavaScriptReturningResult method

  1. @override
Future<Object?> runJavaScriptReturningResult(
  1. String javaScriptInstanceId,
  2. String javaScript
)
override

Evaluates the given JavaScript code javaScript in the context of the javascript environment with id javaScriptInstanceId, and returns the result.

The Future completes with an error if a JavaScript error occurred, or if the type the given expression evaluates to is unsupported.

Implementation

@override
Future<Object?> runJavaScriptReturningResult(
  String javaScriptInstanceId,
  String javaScript,
) async {
  final state = _requireJsRuntimeState(javaScriptInstanceId);
  final runtime = state.runtime;

  try {
    final result = await runtime.evaluateAsync(javaScript);
    if (result.isError) {
      throw JavaScriptDarwinExecutionException.fromResult(
          runtime, result, StackTrace.current);
    }

    if (!result.isPromise) {
      try {
        return runtime.convertValue(result);
      } on TypeError {
        return result.stringResult;
      }
    }

    final promiseResult = await runtime.handlePromise(result);
    if (promiseResult.isError) {
      throw JavaScriptDarwinExecutionException.fromResult(
        runtime,
        promiseResult,
        StackTrace.current,
      );
    }

    try {
      return runtime.convertValue(promiseResult);
    } on TypeError {
      return promiseResult.stringResult;
    }
  } catch (e, s) {
    if (e is JavaScriptDarwinExecutionException) {
      rethrow;
    }
    if (e is JsEvalResult) {
      throw JavaScriptDarwinExecutionException.fromResult(
        runtime,
        e,
        s,
      );
    }
    rethrow;
  }
}