[英]Javascript promise implementation
在 javascript 中實現以下最佳方法是什么。
/*
A --|
|-- D --|
B --| |-- E
|
C ----------|
每個節點都是一個異步作業,由setTimeout
說明。
A、B、C可以同時運行。
D,需要等待A和B完成。
E 需要等待 C 和 D 完成。
我如何實現一個接受上述節點作為參數的接口,這將負責上述實現。 不確定是否可以使用async
/ await
或 JavaScript promise 以及優缺點最好實現什么。
這是您可以使用的 class Task
。 創建一個時,您需要為其提供一個名稱、一個異步 function(將在任務可以啟動時調用)以及此任務所依賴的其他任務實例的列表:
class Task { constructor(name, asyncWork, ...neededTasks) { this.promise = (async () => { await Promise.all(neededTasks.map(task => task.promise)); console.log("start " + name); await asyncWork(); console.log("complete " + name); })(); } } // Utility function to mimic some asynchronous work, using setTimeout: const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); // Define the tasks. Note that they will automatically call // the given function if there are no other tasks to wait for: let a = new Task("a", () => delay(1000)); let b = new Task("b", () => delay(1500)); let c = new Task("c", () => delay(2000)); let d = new Task("d", () => delay(1000), a, b); let e = new Task("e", () => delay(1000), c, d);
創建任務時,會為其創建 promise。 它存儲在其promise
屬性中。 此 promise 僅在以下情況下才會解決:
這兩個步驟是鏈接在一起的,因此在第一步的承諾得到解決之前,實際工作不會開始。
/* A --| |-- D --| B --| |-- E | C ----------| */ let A = new Promise((resolve, reject) => { setTimeout(() => { resolve("im from A"); }, 0); }); let B = new Promise((resolve, reject) => { setTimeout(() => { resolve("im from B"); }, 0); }); let C = new Promise((resolve, reject) => { setTimeout(() => { resolve("im from C"); }, 0); }); let D = new Promise((resolve, reject) => { setTimeout(() => { resolve("im from D"); }, 0); }); let E = new Promise((resolve, reject) => { setTimeout(() => { resolve("im from E"); }, 0); }); (async () => { let [stringOfA, stringOfB] = await Promise.all([A, B]); let [stringOfD, stringOfC] = await Promise.all([D, C]); let stringOfE = await E; console.log(stringOfA, stringOfB, stringOfC, stringOfD, stringOfE); })();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.