![](/img/trans.png)
[英]Javascript. Transform synchronous function as asynchronous using callbacks, promises, async/await, generators
[英]Mixing asynchronous and synchronous work with async/await and/or promises in javascript
更新:我認為我對 async/await 的問題比鏈接的建議更微妙,並更新了問題的標題,希望能更好地反映這一點。 我特別關心如何開始一些可能需要一段時間的異步工作——但不會影響需要按順序發生的大部分頁面邏輯——然后等待異步工作完成,然后再繼續頁面邏輯的一個子集,它依賴於異步邏輯。 答案基本上是相同的( await Promise.all
),但對我來說,接受的答案為我的問題提供的清晰度比鏈接的答案更有價值(在使用await Promise.all
之前將順序邏輯抽象為它自己的異步函數await Promise.all
)。
我很難確定這在 javascript 中是否可行(開頭標有“XXX”的注釋塊是我正在努力使用的代碼(假設任務 1-4 必須按順序執行並且不能並行化) )):
document.addEventListener('DOMContentLoaded', () => {
// Kick off some asynchronous piece of work that potentially takes some
// time (for instance, opening and upgrading an indexedDB) but that should
// not hold up other work that should happen in the meantime (ie: executing
// tasks 1-3).
asynchronousSetup(); // 1000 - 1500 ms of work
// Do a bunch of other stuff that should happen in sequence and as quickly
// as possible (to enable meaningful user interaction in the client).
executeTask1(); // 300 - 400 ms of work
executeTask2(); // 300 - 400 ms of work
executeTask3(); // 300 - 400 ms of work
// XXX Wait for completion of asynchronousSetup() before proceeding with
// any additional work that is also necessary for meaningful user
// interaction in the client, but that requires that the work done in
// asynchronousSetup() is completely finished.
if (/* asynchronousSetup() complete */) {
executeTask4(); // Relies on work done in tasks 1-3 and asynchronousSetup()
}
});
我熟悉 javascript 中的 async/await 和 promises,但我還沒有看到他們有能力完成這類事情的任何演示——我覺得像代碼氣味一樣——設置間隔或超時來檢查用於在觸發executeTask4()
之前確保asynchronousSetup()
已完成的一些公共變量的初始化。
如果我可以這樣做,那將是非常甜蜜的:
// ...Same initial code as above.
const initialized = asynchronousSetup();
// ...Same intervening code as above.
if (await initialized) {
executeTask4();
}
假設asynchronousSetup()
被適當地裝飾為async
:
async function asynchronousSetup() {
// Logic of asynchronousSetup()
}
但我以前試過沒有成功。
謝謝,很抱歉,如果這是一個明顯的問題; 我的搜索或代碼實驗都沒有運氣。 我有一種感覺,一旦有人指出如何實現這一點,我就會感到非常愚蠢……但我會接受; 在我的理解中,這感覺像是一個很大的障礙,在我可以編寫產生良好 UX 的高性能 javascript 之前,我需要克服它;p
如果我正確地關注您,則您必須同時執行 asyncSetup 和 3 個任務(但這 3 個任務必須按順序完成)。 只有在完成所有 4 個任務之后,您才想要繼續執行最后一個任務。 像這樣的事情似乎可以滿足您的要求:
//Provide an async function that does your 3 tasks in the correct order
const doTasks = async () => {
await executeTask1(); // 300 - 400 ms of work
await executeTask2(); // 300 - 400 ms of work
await executeTask3(); // 300 - 400 ms of work
}
document.addEventListener('DOMContentLoaded', async () => {
//Do the setup and the tasks concurrently
await Promise.all([asynchronousSetup(), doTasks()])
//Once all of the previous tasks are done, do the last task
executeTask4()
});
這假設您的所有任務都是異步的,或者返回 Promises。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.