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

标签 javascript modal-dialog closures ui-thread

我正在 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/

相关文章:

javascript - 如何通过单击来检索值并检索 id?

javascript - 带有复选框和链接的 jQuery 模式对话框

twitter-bootstrap - Bootstrap 3 与远程 Modal

javascript - eventListener 内的代码没有立即调用?

javascript - Meteor React 状态传递给子组件未更新

javascript - Angular UI-Router - 直接在模板 url 上使用 "resolve"

javascript - javaScript中 "item"对象来自哪里

javascript - 如何使用最后一个弹出模态上的关闭按钮关闭多个 Bootstrap 模态

javascript - 关于node.js回调中的 'this'

javascript - 闭包期间变量存储在哪里?