wordpress獲取當前頁面鏈接seo搜索優(yōu)化專員
如何實現(xiàn)異步并發(fā)限制
文章目錄
- 如何實現(xiàn)異步并發(fā)限制
- 方法1
- 注意點
- 方法2
- 題目要求
- 實現(xiàn)方法
- 注意點
之前一直沒有系統(tǒng)的去總結(jié)異步并發(fā)限制的實現(xiàn)思路,今天就來做個總結(jié)吧
方法1
只有一個變量
pool:代表正在執(zhí)行中的任務(wù)中的集合
function sleep(name, timeOut) {return new Promise(resolve => {console.log(`${name}開始了`);setTimeout(() => {console.log(`${name}結(jié)束了`);resolve();}, timeOut);})}const tasks = [() => sleep(1, 1000),() => sleep(2, 2000),() => sleep(3, 3000),() => sleep(5, 6000),() => sleep(8, 8000),];async function parallelLimit(tasks, limit = 2) {// 正在執(zhí)行中的任務(wù)的集合const pool = new Set();for (const task of tasks) {const promise = task();pool.add(promise);promise.then(() => pool.delete(promise));if (pool.size >= limit) {await Promise.race(pool);}}return Promise.all(pool);}parallelLimit(tasks).then(() => {console.log('任務(wù)已全部執(zhí)行');})
注意點
- 此時的 pool 代表的是:正在執(zhí)行中的任務(wù)中的集合
- 使用 Promise.race 這種方式不能保證執(zhí)行順序,若要求要按順序執(zhí)行,請看第二種方法
方法2
題目要求
要求實現(xiàn) Scheduler 函數(shù),完成異步并發(fā)限制數(shù)為2的功能,且需要保證執(zhí)行順序
const scheduler = new Scheduler(2);const timeout = (time) =>new Promise((resolve) => {setTimeout(resolve, time);});const addTask = (time, order) => {scheduler.add(() => timeout(time).then(() => console.log(order)))
}addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')// 500ms時,2完成,輸出2
// 800ms時,3完成,輸出3
// 1000ms時,1完成,輸出1
// 1200ms時,4完成,輸出4
實現(xiàn)方法
function Scheduler(limit) {// 模擬隊列,保存所有任務(wù)this.pool = [];// 當前正在執(zhí)行任務(wù)的數(shù)目this.count = 0;this.add = function (fn) {this.pool.push(fn);this.run();}this.run = function () {if (this.pool.length && this.count < limit) {const task = this.pool.shift(); // 保證執(zhí)行順序this.count++;task().then(() => {this.count--;this.run();})}}
}const scheduler = new Scheduler(2);const timeout = (time) =>new Promise((resolve) => {setTimeout(resolve, time);});const addTask = (time, order) => {scheduler.add(() => timeout(time).then(() => console.log(order)))
}addTask(1000, '1')
addTask(500, '2')
addTask(300, '3')
addTask(400, '4')// 500ms時,2完成,輸出2
// 800ms時,3完成,輸出3
// 1000ms時,1完成,輸出1
// 1200ms時,4完成,輸出4
注意點
- pool 代表保存所有任務(wù)的數(shù)組
- count 代表當前正在執(zhí)行任務(wù)的數(shù)目
- 保證順序:需要從數(shù)組中順序取出并執(zhí)行
兩個方法各變量代表的含義不同,實現(xiàn)的思路也就不同,要好好區(qū)分兩種方法的思想,不然會混淆(像我一樣??????)
道阻且長,面試加油,邊復(fù)習邊查漏補缺吧!!!
passion!!!