1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| function sleep (timeout: number, taskName: string) { return new Promise<void>(resolve => { console.log(`${taskName}开始啦`); setTimeout(() => { console.log(`${taskName}结束啦`); resolve(); }, timeout) }); }
const tasks = [ () => sleep(1000, '睡觉'), () => sleep(2000, '吃饭'), () => sleep(3000, '打游戏'), () => sleep(5000, '写代码'), () => sleep(7000, '做运动'), ];
async function doSomething(tasks:(()=>Promise<void>)[], limit=2) { const taskPool = new Set(); for (const task of tasks) { const promise = task(); taskPool.add(promise); promise.then(() => taskPool.delete(promise)); if (taskPool.size >= limit) { await Promise.race(taskPool); } } return Promise.all(taskPool); }
doSomethin(tasks).then(() => { console.log('任务全部执行完了'); })
function getTasks(urls) { const tasks = []; urls.forEach(url => { tasks.push(() => { new Promise(resolve => { const img = new Image(); img.onload = () => { resolve(); } img.src = url; }) }) }) return tasks; }
doSomething(getTasks(['xxxx.jpg', 'xxxx.png'])).then(() => { console.log('全部执行完了'); })
|