flutter 如何使用Javascript内核的JSObjectMakeDeferredPromise

yrefmtwq  于 2023-03-19  发布在  Flutter
关注(0)|答案(1)|浏览(75)

我使用flutter_jscorelib,我想从javascript对flutter进行异步调用。我使用JSObjectMakeDeferredPromise,在flutter端的异步任务之后,我调用了resolve函数,但是可能没有调用javascript的代码resolve或reject,我没有看到任何关于JSObjectMakeDeferredPromise的文档,请更正我的代码,可能我不理解函数,或者我的代码有bug。
这是我的代码:
//初始化JsContext并注册getUser函数

var _jsContext = JSContext.createInGroup();
var jsGetUserFunction = JSObject.makeFunctionWithCallback(
        _jsContext, 'getUser', Pointer.fromFunction(getUser));

_jsContext.globalObject.setProperty('getUser', jsGetUserFunction.toValue(),
        JSPropertyAttributes.kJSPropertyAttributeNone);

//这是getUser flutter的代码

Pointer getUser(
      Pointer ctx,
      Pointer function,
      Pointer thisObject,
      int argumentCount,
      Pointer<Pointer> arguments,
      Pointer<Pointer> exception) {
   
   var resolve = JSObject.makeFunction(
          _jsContext, 'resolve', JSStringPointer.array(['value']), '', '');

      var reject = JSObject.makeFunction(
          _jsContext, 'reject', JSStringPointer.array(['value']), '', '');

      final promise = JSObject.makeDeferredPromise(_jsContext,
          JSObjectPointer(resolve.pointer), JSObjectPointer(reject.pointer));

      print('created promise');

      fetchUser().then((value) {
        print('fetch done!');

        var pointerValue =
            JSValuePointer(JSValue.makeString(_jsContext, value).pointer);

      
        resolve.callAsFunction(resolve, pointerValue);

        print('resolve')

        return nullptr;
      });

      return promise.pointer;
  }

Future<String> fetchUser() async {
    await new Future.delayed(const Duration(seconds: 3));
    return "user info";
  }

我的javascript代码
试验1

var promiseFunc = getUser();
console.log(promiseFunc);

promiseFunc.then(function(value) {
   console.log(value);
});

输出:

[object Promise]

预期:

[object Promise]
'user info'

测试2:

async function helloJs() {
       await getUser();
       console.log('after wait');
 }
 helloJs();

结果:

calling getUser

预期:

calling getUser
after wait

也许waitgetUser会永远等待,它在等待flutter端的resolve函数调用,我的代码已经调用了resolve函数,但我不知道为什么。

juud5qan

juud5qan1#

你需要重写promise对象的“then”函数,执行如下操作:

JSObjectPointer resolve = JSObjectPointer(nullptr);
JSObjectPointer reject = JSObjectPointer(nullptr);
JSObject promise = JSObject.makeDeferredPromise(context, resolve, reject);
var thenFunc = JSObject.makeFunction(context, "then", JSStringPointer.array(['resolve']), "this.resolve=resolve", "");
promise.setProperty("then", thenFunc.toValue(), JSPropertyAttributes.kJSPropertyAttributeNone);
http.get(Uri.parse(url)).then((response) {
  if (response.statusCode == 200) {
    var resolveFunc = promise.getProperty("resolve");
    print(resolveFunc.string);
    return (JSObject(context, resolveFunc.toObject()!.pointer))
        .callAsFunction(JSObject(context, thisObject), JSValuePointer(JSValue.makeString(context, response.body).pointer));
  }
});

相关问题