简体   繁体   中英

javascript pause function execution until event is triggered

i'm making a javascript widget (for the thingsboard platform). the thingsboard site has some javascript code running (eg 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM