Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

For main functions returning a Future, translate into JS Promises when creating an npm package #64

Merged
merged 5 commits into from
Nov 14, 2020
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions lib/src/npm.dart
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,29 @@ String get _wrapperLibrary {
wrapper.writeln("import $target as module_main;");
}

// Define a JS-interop Future to Promise translator so that we can export
// a Promise-based API
wrapper.writeln("""
@JS()
class Promise<T> {
external Promise(void executor(void resolve(T result), Function reject));
}

Promise<T> _futureToPromise<T>(Future<T> future) {
return new Promise<T>(allowInterop((resolve, reject) {
future.then(resolve, onError: reject);
}));
}
BobobUnicorn marked this conversation as resolved.
Show resolved Hide resolved

Object _translateReturnValue(Object val) {
if (val is Future) {
return _futureToPromise(val);
} else {
return val;
}
}
""");

// Define a JS-interop "exports" field that we can use to export the various
// main methods.
wrapper.writeln("""
Expand Down Expand Up @@ -326,10 +349,11 @@ class _Exports {""");
wrapper.writeln("""
Function _wrapMain(Function main) {
if (main is Object Function()) {
return allowInterop((_) => main());
return allowInterop((_) => _translateReturnValue(main()));
} else {
return allowInterop(
(args) => main(List<String>.from(args as List<Object>)));
(args) => _translateReturnValue(
main(List<String>.from(args as List<Object>))));
}
}""");

Expand Down