简体   繁体   English

如何冻结/停止 JavaScript 执行,直到 function 完成

[英]How to freeze/stop JavaScript execution until a function is done

I want to know how can I freeze/stop JavaScript execution until a function is finished (Using JavaScript/NodeJS).我想知道如何冻结/停止 JavaScript 执行,直到 function 完成(使用 JavaScript/NodeJS)。 For example:例如: 在此处输入图像描述

The first line of code in the console shows an alert to the use, JavaScript execution is frozen/stopped until the user clicks ok .控制台中的第一行代码显示了使用警告,JavaScript 执行被冻结/停止,直到用户单击ok 在此处输入图像描述

And when that is done the second line of code will continue to execute完成后,第二行代码将继续执行在此处输入图像描述

Now, I know that I should use async functions to do that, but that isn't working, here's my node code that is loaded in a preload script of a webview in Electron :现在,我知道我应该使用异步函数来做到这一点,但这不起作用,这是我在Electronwebview的预加载脚本中加载的节点代码:

global.alert = async (text) => {
  //replace it with custom alert!
  ipcRenderer.sendToHost('ShowAnAlert', {
    theWebsiteLink: location.href,
    theMessage: text
  });
  var a = await function(){
    return new Promise(resolve => {
      ipcRenderer.on('GetResult', () => {
        console.log("Done!");
        resolve("result");
      });
    });
  }();
  return a;
}

But it doesn't freeze/stop JavaScript execution when it's preformed.但它不会在执行时冻结/停止 JavaScript 执行。 How can I fix that?我该如何解决?

EDIT 1: Ok, turns out that asynchronous isn't the answer that I'm looking for.编辑 1:好的,事实证明异步不是我正在寻找的答案。

global.alert = (text) => {
  //replace it with custom alert!
  ipcRenderer.sendToHost('ShowAnAlert', {
    theWebsiteLink: location.href,
    theMessage: text
  });
  var a = ipcRenderer.on('GetResult', () => {
    console.log("Done!");
  });
  return a;//this is returned as undefined
}

I've removed asynchronous parts in the script.我已经删除了脚本中的异步部分。 But the function isn't freezing/stopping JavaScript execution.但是 function 没有冻结/停止 JavaScript 执行。 Any idea how can I do this?知道我该怎么做吗?

EDIT 2: If this isn't possible to do in pure JavaScript, is there some other ways to do this using Electron native functions or Electron Libraries/modules编辑 2:如果在纯 JavaScript 中无法做到这一点,是否还有其他方法可以使用Electron 本机函数Electron 库/模块来做到这一点

An async function, by definition, is asynchronous and does not stop the execution of the script.根据定义,异步 function 是异步的,不会停止脚本的执行。 If you wanted it to stop the execution, you'd need to remove the asynchronous parts of it (the Promise, async & await).如果您希望它停止执行,则需要删除它的异步部分(Promise,异步和等待)。

The part那个部分

var a = ipcRenderer.on('GetResult', () => {
    console.log("Done!");
  });

is an event listener so it will wait for the "GetResult" event before running the console.log within it.是一个事件侦听器,因此它会在其中运行 console.log 之前等待“GetResult”事件。 This will also return undefined, hence why a is undefined.这也将返回未定义,因此a未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM