簡體   English   中英

使用node.js / electron / javascript在網頁中運行異步命令

[英]Run asynchronous commands in a webpage with node.js / electron / javascript

編輯:使用BrowserWindow

在網頁中一個接一個地啟動javascript命令的最簡單/最佳方法是什么? (異步,不同步)
例如,一個keypress事件觸發了幾個document.write

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> 

使用awaitasync可以完成相同的操作:

 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> 

Promiseasyncawait僅在現代的瀏覽器和節點中實現(這應該適合您的情況,因為您正在使用電子)。 如果您還想支持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); }; } 

這可以通過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(); } }); }); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM