angular dart js interop with async / promise awaited in client
Asked Answered
T

1

5

clientside.js

async function callClientAsyncFuncWithResult () {

    let result = await someService.request();
    return result;
}

page.dart

import 'dart:js' as js;

var result = js.context.callMethod('callClientAsyncFuncWithResult'); 

//I want to do something like var result = await js.context.callMethod('callClientAsyncFuncWithResult'); 

How in AngularDart do you wait for a client side javascript Promise to return with result before continuing execution in dart? Right now it just flows over the call and I've tried setting the result of callMethod to Future or Promise and it never waits.

I don't think my implementation is correct. How can I achieve this?

Talaria answered 7/4, 2019 at 18:56 Comment(0)
H
10

You can easily convert a Javascript Promise to a Dart Future, by using the convertNativePromiseToDartFuture API, which is available in dart:html_common.

A simple implementation might look like :

Javascript :

function myCoolFunc () {
  return new Promise((resolve, reject) => {
    resolve(myLongAwaitedData);
  });
}

Dart Interop file :

@JS()
library coolLib;

import 'package:js/js.dart';
import 'dart:async';

@JS()
external Future<T> myCoolFunc ();

Dart file :

import 'dart:html_common';
import 'cool_lib.dart';

main() async {
  var myVar = await convertNativePromiseToDartFuture(myCoolFunc());
  print(myVar);
}

I found this deeply buried in the Gitter of the Dart Sdk. I hope it can help future Angular Dart users.

Update : This API has changed in Dart 2.6 convertNativePromiseToDartFuture has been replaced with promiseToFuture

Hung answered 29/9, 2019 at 13:49 Comment(1)
@SlimShady Updated answer to reflect new APIHung

© 2022 - 2024 — McMap. All rights reserved.