Handle asyncronus javascript calls from GDScript

Godot Version

4.2

Question

Hi, I’m trying to get a String from a database using JavaScriptBridge calling a function called getOpenField() which uses a “Promise” object and I don’t know how to handle that object from GDScript. With this I mean wait for the promise state to be " fulfilled" and then get the String from that object.

I think once you have the promise JavaScript object you need to call then method with a fulfilled callback and a rejection callback.

Js_promise.then(success_cb, failed_cb)

func success_cb(args):
  ...
Func failed_cb(args):
 ...

I think I’m not understanding something because if I use the then function from GDScript like this

var openField= JavaScriptBridge.eval("getOpenField()")
openField.then(success_cb, failed_cb)

It gives me this error

USER SCRIPT ERROR: Invalid call. Nonexistent function ‘then’ in base ‘Nil’.

But if I create a callback and call it from the JavaScriptBridge.eval like this

var js_Callback_success = JavaScriptBridge.create_callback(success_cb)
var js_Callback_failed = JavaScriptBridge.create_callback(failed_cb)

func _ready():
	JavaScriptBridge.eval("getOpenField().then(success_cb,failed_cb)")

func success_cb(args):
	...
func failed_cb(args):
	...

ReferenceError: success_cb is not defined

I’ve tried calling from the eval using both GDScript var js_Callback_success and success_cb and the error message is the same

this is probably because javascriptbridge.eval() returns a Variant, and Godot doesn’t have a promise Variant class.

you need a JavaScriptObject class which is usually gotten with JavaScriptBridge.get_interface(<interface string>)

You may need to create a custom interface that will wrap your function with a the promise. and you can abstract the then function.

// suedo js
const MyInterface = {
    getOpenField: function () { },
    then: function (args) { },
};  
# suedo gd
var my_interface : JavaScriptObject = JavaScriptBridge.get_interface("MyInterface")

There are also other means to setup callbacks documented in the JavaScriptBridge class.

-----

this is because i did not define a valid function body for the callback in my post. just replace the three periods with the pass keyword if you don’t have a function in mind yet. (I was attempting to convey that you will implement whatever you need.)

func success_cb(args):
	pass

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.