[英]javascript pause function execution until event is triggered
i'm making a javascript widget (for the thingsboard platform). 我正在制作一个javascript小部件(适用于Thingsboard平台)。 the thingsboard site has some javascript code running (eg
do_some_things
) which i can not modify. 物联网站点上有一些我无法修改的JavaScript代码(例如
do_some_things
)正在运行。 my widget can define functions like func_1
that will be run by the thingsboard site. 我的小部件可以定义诸如
func_1
功能,这些功能将由Thingsboard网站运行。
//### 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. 在
func_1
我想返回一些我从websocket服务器检索到的字符串。 how do i block the execution of func_1
until i have the websocket message? 在
func_1
websocket消息之前,如何阻止func_1
的执行?
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. 我已经查看了promises和await,但是我看不到有什么帮助,因为我无法在
func_1
完成并返回其值之前允许func_2
运行。
(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.
如果您无法修改do_some_things,将会遇到困难。 You could queue your work, but if do_some_things ever expects a return value then that will be impossible to provide synchronously.
您可以将工作排队,但是如果do_some_things期望返回值,那么将无法同步提供。 One cannot block on a websocket.
一个人无法阻止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. 我接受了这个问题,用JavaScript无法解决,只要不能编辑功能
do_some_things
并想通过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. 我现在找到了一种解决方法,方法是在与websocket服务器相同的机器上设置一个小型http服务器,该服务器提供包含返回字符串的json文件。 i can request the file in a way that blocks the execution of
func_1
like so: 我可以通过阻止
func_1
的执行方式来请求文件, func_1
所示:
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. 因为XMLHttp支持与websocket不同的同步请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.