[英]Waiting for asynchronous function, which doesn't take callback and doesn't return a promise, to be executed without changing the other function
我目前正在嘗試向使用JavaScript編寫的現有Web應用程序添加一些功能。 我的問題是我想調用一個函數,該函數再次調用一些異步函數,並且我想在不執行所有其他函數之前執行一個函數。
我正在調用的函數不會接受回調,也不會返回Promise(當然,這是非常糟糕的做法)。
我可以重構現有的函數,以便我正在調用的函數返回一個Promise,但這將需要大量的時間和精力。
因此,對我來說,理想的解決方案是一種技術,它允許我等待已調用的函數,然后再執行該函數再次調用的所有函數。
另一個可以接受的選擇是一種技術,它允許我在所有異步功能都已執行之后執行功能。
因此,將其轉移到一個簡單的示例中,我想在執行函數doSomethingAsync
之后執行一個函數,而不更改此函數。
var doSomethingAsync = () => {
setTimeout(() => { console.log("do Something Async") }, 1000);
};
// do something after doSomethingAsync has been executed ...
我嘗試過使用setTimeout()和零millisecs函數,但是由於它在doSomethingAsync
函數之前執行,因此不起作用,在這個簡單示例中,我知道這一點。
有很多選項可以在doSomethingAsync
之后執行某些操作,但是我需要一種技術,使我可以在doSomethingAsync
之后執行某些操作而無需更改此功能。
任何提示都非常感謝。
如果不更改doSomethingAsync
就無法實現所需的目標。 該函數立即完成,並且無法檢測到setTimeout
何時完成。 除非您能找到其他需要監視的副作用,否則您很不幸。
從技術上講,在doSomethingAsync
完成執行后立即執行某些操作很容易。 它幾乎立即完成。 您無法做的是在setTimeout
觸發器之后執行一些操作。 因為doSomethingAsync
不會返回與其內部所做的任何聯系。
您似乎正在尋找await
關鍵字。
async function waitForMe() {
console.log("I take time to execute")
}
async function waitsForOthers() {
console.log("I am going to print right now")
await waitForMe() //***
console.log("Now that that's done, I am going to print")
}
您可以將上述功能更改為
var doSomethingAsync = () => { setTimeout(() => { console.log("do Something Async"); youWantToExecuteAtLast(); }, 1000); }; // do something after doSomethingAsync has been executed ... function youWantToExecuteAtLast() { alert("This is the end"); }; doSomethingAsync();
對於多個電話,
var counter = 0; var doSomethingAsync = (timer) => { setTimeout(() => { console.log("do Something Async : ",(counter+1)); counter++; youWantToExecuteAtLast(); }, timer); }; // do something after doSomethingAsync has been executed ... function youWantToExecuteAtLast() { if(counter === 3) alert("Three calls are done"); }; doSomethingAsync(2000); doSomethingAsync(4000); doSomethingAsync(6000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.