0

i'm making a javascript widget (for the thingsboard platform). the thingsboard site has some javascript code running (e.g. do_some_things) which i can not modify. my widget can define functions like func_1 that will be run by the thingsboard site.

//### THINGSBOARD CODE (can not modify!) ###
function do_some_things() {
    ...
    func_1();
    func_2();
    ...
}

//### WIDGET CODE (can modify!) ###
function func_1() {

    socket = new WebSocket("ws://192.168.137.4:8081/");
    socket.onmessage=function(evt) { 
        settings_string = evt.data;    
    }

    /* wait for a message here!*/

    return settings_string;
}

in func_1 i would like to return some string that i retrive from a websocket server. how do i block the execution of func_1 until i have the websocket message?

i've had a look at promises and await, but i don't see how that can help me as i cant allow func_2 to run before func_1 is done and has returned its value.

(i don't care if the whole site freezes while it's waiting for the websocket)

cyrili101
  • 101
  • 2
  • is there any reason why you can't just put the `func_2()` call inside the `socket.onmessage` callback, *instead* of in `do_some_things`? – David784 Feb 19 '19 at 15:35
  • You can't, freeze or no freeze.. Ideally `do_some_things` needs to be able to handle `async` code, either using callbacks or promises. – Keith Feb 19 '19 at 15:42
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Keith Feb 19 '19 at 15:43
  • 1
    If you cannot modify `do_some_things`, you'll have a hard time. You could queue your work, but if `do_some_things` ever expects a return value then that will be *impossible* to provide synchronously. One cannot block on a websocket. – Bergi Feb 19 '19 at 15:48

1 Answers1

0

Thank you Bergi for the comment.

If you cannot modify do_some_things, you'll have a hard time. You could queue your work, but if do_some_things ever expects a return value then that will be impossible to provide synchronously. One cannot block on a websocket. – Bergi

i accepted that the problem is not solveable in javascript as long as one can not edit the function do_some_things and wants to retrieve data via websockets.

i have now found a workaround by setting up a small http server on the same machine as the websocket server which provides a json file containing the return string. i can request the file in a way that blocks the execution of func_1 like so:

function func_1() {
    var request = new XMLHttpRequest();
    request.open('GET', "http://192.168.137.4:8082/", false);
    request.send(null);
    if (request.status == 200) {
        return request.responseText;
    } else {
        return "";
    }
}

as XMLHttp support synchronous requests unlike websocket.

cyrili101
  • 101
  • 2