Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular dart js interop with async / promise awaited in client

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?

like image 503
james Avatar asked Mar 05 '23 05:03

james


1 Answers

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

like image 94
Standaa - Remember Monica Avatar answered Mar 19 '23 01:03

Standaa - Remember Monica