编辑:使用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(){
...
}
答案 0 :(得分:2)
在代码运行之前等待操作的最简单方法是使用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
仅在现代浏览器和节点中实现(由于您正在使用电子,因此应该适合您的情况)。如果您还想支持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);
};
}
答案 1 :(得分:0)
使用async / await语法可以做到这一点。要等待按键,请将事件侦听器添加到keypress
事件中。在此示例中,当用户按下Enter键时,将打印第2行。
async function myProgram() {
console.log('line 1')
await myAsyncFunction();
console.log('line 2');
}
myProgram();
async function myAsyncFunction(){
return new Promise((resolve) => {
document.addEventListener('keypress', function _listener(event) {
if (event.keyCode === 13) {
document.removeEventListener('keypress', _listener);
resolve();
}
});
});
}