我正在用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.
}
由于JavaScript的性质,您不能阻止代码。唯一的方法是使用计时器来检查返回值,承诺或对此的更好解决方案:回调:
function main()
{
showDialog({
title: "Warning",
text: "Do you want to continue?",
buttons: ["OK", "Cancel"],
onClose: function(result) {
if (result == "OK") {
performAction1();
} else {
console.log("Cancelled");
}
}
});
}
function showDialog(options)
{
$("#dialog .title").innerText = options.title;
$("#dialog .text").innerText = options.text;
$(".button").hide();
for (var i = 0; i < options.buttons.length; i++) {
$(".button:nth-child(" + i + ")")
.show()
.innerText(options.buttons[i])
.click(() => {
$("#dialog").hide();
options.onClose(options.buttons[0]); // Perform the callback
}
}
#("#dialog").show();
}
事实证明,异步/等待可以满足我的需求。使用await关键字调用函数将在那时“阻塞”线程,直到函数的诺言得以解决。为了能够使用await关键字,主要功能必须使用async关键字。
async function main()
{
let dialog = new CustomDialog();
let result = await dialog.show();
if (result === "OK") performAction();
}
class CustomDialog
{
constructor()
{
this.closeResolve = null;
this.returnValue = "OK";
}
show()
{
// Code to show the dialog here
// At the end return the promise
return new Promise(function(resolve, reject)
{
this.closeResolve = resolve;
}.bind(this));
}
close()
{
// Code to close the dialog here
// Resolve the promise
this.closeResolve(this.returnValue);
}
}