首页 > 解决方案 > 使用 node.js / electron / javascript 在网页中运行异步命令

问题描述

编辑:使用BrowserWindow.

在网页中一个接一个地启动 javascript 命令的最简单/最好的方法是什么?(异步的,不同步的)
比如几个由一个事件document.write触发。keypress

document.write("line 1");
wait_for_key_press();
document.write("line 2");
wait_for_key_press();
document.write("line 3");
wait_for_key_press();
document.write("line 4");
...

function wait_for_key_press(){
 ...
}

标签: javascriptnode.jselectron

解决方案


在运行代码之前等待操作的最简单方法是使用 Promise 或事件侦听器(或两者兼而有之)。例如:

var resolves = [];

document.querySelector("#start").addEventListener("click", doActions);
document.querySelector("#stop-wait").addEventListener("click", function() {
  resolves.forEach(function(resolve) {
    resolve();
  });
  resolves = [];
});

function waitButtonClick() {
  return new Promise(function(resolve) {
    resolves.push(resolve);
  });
}

function doActions() {
  console.log("Step 1");
  waitButtonClick().then(function() {
    console.log("Step 2");
  });
}
<button id="start">Start Actions</button>
<button id="stop-wait">Stop waiting</button>

同样可以使用awaitand来完成async

var resolves = [];

document.querySelector("#start").addEventListener("click", doActions);
document.querySelector("#stop-wait").addEventListener("click", function() {
  resolves.forEach(function(resolve) {
    resolve();
  });
  resolves = [];
});

function waitButtonClick() {
  return new Promise(function(resolve) {
    resolves.push(resolve);
  });
}

async function doActions() {
  console.log("Step 1");
  await waitButtonClick();
  console.log("Step 2");
}
<button id="start">Start Actions</button>
<button id="stop-wait">Stop waiting</button>

Promiseasync并且await仅在现代浏览器和节点中实现(应该适合您的情况,因为您使用的是电子)。如果你还想支持 IE,你可以创建一个自定义Promisepolyfill:

if (typeof window["Promise"] !== "function") {
  window["Promise"] = function(callBack) {
    var catchList = [];
    var thenList = [];
    this.then = function(callBack) {
      if (typeof callBack === "function") thenList.push(callBack);
      return this;
    };
    this.catch = function(callBack) {
      if (typeof callBack === "function") catchList.push(callBack);
      return this;
    };

    function resolve(result) {
      thenList.forEach(function(callBack) {
        callBack(result);
      });
    };

    function reject(error) {
      catchList.forEach(function(callBack) {
        callBack(error);
      });
    };
    callBack(resolve, reject);
  };
}


推荐阅读