我正在 JavaScript 的 HTML 层中制作一个对话框。当我调用它时,我希望它的行为就像我调用内置警报框时一样。它应该在调用时产生 GUI 线程,然后在关闭时在下一个代码行恢复执行。从调用者的 Angular 来看,它的行为就好像它阻塞了 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 对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61184865/