【发布时间】:2020-04-13 09:26:34
【问题描述】:
我正在用 Javascript 在 HTML 层中制作一个对话框。当我调用它时,我希望它的行为就像我调用内置警报框时一样。它应该在调用时产生 GUI 线程,然后在它关闭时在下一个代码行上恢复执行。从调用者的角度来看,它的行为就好像它阻塞了 GUI 线程。这在 Javascript 中可行吗?
在下面的主函数中,我希望在调用 showDialog 时保留函数的执行状态。然后显示对话框,并接收点击事件等,当它最终关闭时,我希望将返回值传递回结果变量并在主函数中恢复执行。这有可能吗?我并没有考虑实际阻塞 GUI 线程,因为那样对话框将不起作用。
function main()
{
// Show the dialog to warn
let result = showDialog("Warning", "Do you want to continue?", ["OK", "Cancel"]);
// Do some stuff.
if (result === "OK") performAction();
}
// This function shows a custom modal dialog (HTML layer), and should only return the GUI
// thread when the user has clicked one of the buttons.
function showDialog(title, text, buttons)
{
// Code here to draw the dialog and catch button events.
}
【问题讨论】:
-
这能解决您的问题吗? stackoverflow.com/questions/6807799/…
-
谢谢@Shubham。确实如此。我知道承诺和回调方法。这就是我目前用来解决问题的方法。但我认为它使代码丑陋且难以阅读。所以我希望我可以巧妙地使用 yield 关键字,但我还没有弄明白。
标签: javascript modal-dialog closures ui-thread