带有线程暂停/恢复的Javascript对话框



我正在用Javascript在HTML层中制作一个对话框。当我调用它时,我希望它的行为就像我调用内置的Alert框时一样。它应该在被调用时产生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.
}

事实证明async/await可以满足我的需要。使用await关键字调用函数将在此时"阻塞"线程,直到函数的promise得到解决。为了能够使用await关键字,main函数必须使用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);
}
}

由于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();
}

最新更新