编辑:使用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(){
...
}
最佳答案
在代码运行之前等待操作的最简单方法是使用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>
使用
await
和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>
Promise
, async
和 await
仅在现代浏览器和 Node 中实现(由于您正在使用 Electron ,因此应该适合您的情况)。如果您还想支持IE,则可以创建一个自定义的Promise
polyfill: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);
};
}