B4J Question [WebApp] Send result of an asynchronous JS-Function back to WebSocket?

Kiffi

Well-Known Member
Licensed User
Longtime User
Hello,

i start from a Websocket an asynchronous JS-Function.

B4X:
GoogleMapsGeocoder2 = function(address) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                var CSV = "";
                $.each(results, function(key, result) {
                    CSV += result.formatted_address + ";";
                    CSV += result.geometry.location + "\n";
                });
                // ? How to send CSV to the Websocket?
            } else {
                // ? How to send "No results found" to the Websocket?
            }
        } else {
            // ? How to send "Geocode was not successful for the following reason: " + status to the Websocket?
        }
    });
};

How can i send the result back to the Websocket?

Thanks in advance and Greetings ... Peter
 

billzhan

Active Member
Licensed User
Longtime User
You may try "return". Not sure if it works for you.

An example to fetch timezone from client,it works for me:
B4X:
Dim tz As String ="return new Date().getTimezoneOffset();"
Dim tzfuture As Future=ws.EvalWithResult(tz,Null)
Log("tz:  "&tzfuture.Value)
 
Upvote 0

Kiffi

Well-Known Member
Licensed User
Longtime User
Hello billzhan,

thanks for your reply!

unfortunately this doesn't work for me. The function returns immediately. The result returns later.

Therefore i need to know how to call a websocket-sub manually

something like this (Pseudocode):
B4X:
myFunction = function() {
 doSomeAsynchronousStuff(function() {
   callAWebsocketSubWhenReady(myWebsocketSub, Result);
 });
};

Greetings ... Peter
 
Upvote 0

billzhan

Active Member
Licensed User
Longtime User
I think of a workaround, you can have a hidden button, when result is ready, pass the result to button value and then click it.

In button_click event, you can get the val.
 
Upvote 0

Kiffi

Well-Known Member
Licensed User
Longtime User
thanks, billzhan. I think i got it.

I prepare the Websocket-Code the following way:
B4X:
Sub Class_Globals
    [...]
    Dim RequestLatLng As JQueryElement
End Sub

[...]

Private Sub RequestLatLng_OnSuccess(Params As Map)
    Dim Result As String
    Result = Params.Get("result") 
    WS.Alert(Result)
End Sub

Private Sub RequestLatLng_OnError(Params As Map)
    Dim Result As String
    Result = Params.Get("result") 
    WS.Alert(Result)
End Sub

and then i can send:
B4X:
b4j_ws.send(JSON.stringify({type: 'event', event: 'RequestLatLng_OnSuccess', params: {result:theResult} }));
or
B4X:
b4j_ws.send(JSON.stringify({type: 'event', event: 'RequestLatLng_OnError', params: {result:theResult} }));

Greetings ... Peter
 
Upvote 0
Top