javascript - 使用 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(){
...
}
解决方案
在运行代码之前等待操作的最简单方法是使用 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
and来完成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);
};
}
推荐阅读
- tensorflow - 加载并运行测试 .trt 模型
- css - 两个不同大小的图像具有相等的高度和父级的填充宽度
- amazon-web-services - 部署到时 S3 PutObject 访问被拒绝
- odoo - 从 Odoo 12 中 POS 收据上的日期时间字段中删除时间
- python - 为什么在cmd中输入命令后没有出现python的版本?
- reactjs - 在状态的先前值更新后如何更新状态中的项目?
- java - 用于音频的 Java 多线程
- swiftui - SwiftUI 识别鼠标悬停
- android - Gradle Build 失败并出现异常 android studio
- c# - 具有抽象类型转换的泛型类型