欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript/TypeScript 實現(xiàn)并發(fā)請求控制的示例代碼

 更新時間:2021年01月18日 08:37:48   作者:鳳晴鈴玉  
這篇文章主要介紹了JavaScript/TypeScript 實現(xiàn)并發(fā)請求控制,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

場景

假設(shè)有 10 個請求,但是最大的并發(fā)數(shù)目是 5 個,并且要求拿到請求結(jié)果,這樣就是一個簡單的并發(fā)請求控制

模擬

利用 setTimeout 實行簡單模仿一個請求

let startTime = Date.now();
const timeout = (timeout: number, ret: number) => {
 return (idx?: any) =>
 new Promise((resolve) => {
  setTimeout(() => {
  const compare = Date.now() - startTime;
  console.log(`At ${Math.floor(compare / 100)}00 return`, ret);
  resolve(idx);
  }, timeout);
 });
};

const timeout1 = timeout(1000, 1);
const timeout2 = timeout(300, 2);
const timeout3 = timeout(400, 3);
const timeout4 = timeout(500, 4);
const timeout5 = timeout(200, 5);

通過這樣來模擬請求,本質(zhì)就是 Promise

沒有并發(fā)控制的時候

const run = async () => {
 startTime = Date.now();
 await Promise.all([
 timeout1(),
 timeout2(),
 timeout3(),
 timeout4(),
 timeout5(),
 ]);
};

run();

At 200 return 5
At 300 return 2
At 400 return 3
At 500 return 4
At 1000 return 1

可以看到輸出是 5 2 3 4 1 ,按 timeout 的時間輸出了

并發(fā)條件

假設(shè)同時間最大并發(fā)數(shù)目是 2,創(chuàng)建一個類

class Concurrent {
 private maxConcurrent: number = 2;

 constructor(count: number = 2) {
 this.maxConcurrent = count;
 }
}

第一種并發(fā)控制

想一下,按最大并發(fā)數(shù)拆分 Promise 數(shù)組,如果有 Promise 被 fulfilled 的時候,就移除掉,然后把 pending 狀態(tài)的 Promise ,加進(jìn)來。Promise.race 可以幫我們滿足這個需求

class Concurrent {
 private maxConcurrent: number = 2;

 constructor(count: number = 2) {
 this.maxConcurrent = count;
 }
 public async useRace(fns: Function[]) {
 const runing: any[] = [];
 // 按并發(fā)數(shù),把 Promise 加進(jìn)去
 // Promise 會回調(diào)一個索引,方便我們知道哪個 Promise 已經(jīng) resolve 了
 for (let i = 0; i < this.maxConcurrent; i++) {
  if (fns.length) {
  const fn = fns.shift()!;
  runing.push(fn(i));
  }
 }
 const handle = async () => {
  if (fns.length) {
  const idx = await Promise.race<number>(runing);
  const nextFn = fns.shift()!;
  // 移除已經(jīng)完成的 Promise,把新的進(jìn)去
  runing.splice(idx, 1, nextFn(idx));
  handle();
  } else {
  // 如果數(shù)組已經(jīng)被清空了,表面已經(jīng)沒有需要執(zhí)行的 Promise 了,可以改成 Promise.all
  await Promise.all(runing);
  }
 };
 handle();
 }
}

const run = async () => {
 const concurrent = new Concurrent();
 startTime = Date.now();
 await concurrent.useRace([timeout1, timeout2, timeout3, timeout4, timeout5]);
};

At 300 return 2
At 700 return 3
At 1000 return 1
At 1200 return 5
At 1200 return 4

可以看到輸出已經(jīng)變了,為什么會這樣呢,分析一下,最大并發(fā)數(shù) 2

// 首先執(zhí)行的是 1 2
1 需要 1000 MS 才執(zhí)行完
2 需要 300 MS

2 執(zhí)行完,時間線變成 300 移除 2 加入 3 開始執(zhí)行 3
3 需要 400MS 執(zhí)行完時間變成 700 移除 3 加入 4 開始執(zhí)行 4
4 需要 500MS
時間線來到 1000MS,1 執(zhí)行完 移除 1 加入 5 開始執(zhí)行 5
時間線來到 1200MS,4 和 5 剛好同時執(zhí)行完

第二種方案

可以利用 await 的機(jī)制,其實也是一個小技巧

await 表達(dá)式會暫停當(dāng)前 async function 的執(zhí)行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調(diào)的 resolve 函數(shù)參數(shù)作為 await 表達(dá)式的值,繼續(xù)執(zhí)行 async function。

如果當(dāng)前的并發(fā)數(shù)已經(jīng)超過最大的并發(fā)數(shù)目了,可以設(shè)置一個新的 Promise,并且 await,等待其他的請求完成的時候,resolve,移除等待,所以需要新增兩個狀態(tài),當(dāng)前的并發(fā)數(shù)目,還有用來存儲 resolve 這個回調(diào)函數(shù)的數(shù)組

class Concurrent {
 private maxConcurrent: number = 2;
 private list: Function[] = [];
 private currentCount: number = 0;

 constructor(count: number = 2) {
 this.maxConcurrent = count;
 }
 public async add(fn: Function) {
 this.currentCount += 1;
 // 如果最大已經(jīng)超過最大并發(fā)數(shù)
 if (this.currentCount > this.maxConcurrent) {
  // wait 是一個 Promise,只要調(diào)用 resolve 就會變成 fulfilled 狀態(tài)
  const wait = new Promise((resolve) => {
  this.list.push(resolve);
  });
  // 在沒有調(diào)用 resolve 的時候,這里會一直阻塞
  await wait;
 }
 // 執(zhí)行函數(shù)
 await fn();
 this.currentCount -= 1;
 if (this.list.length) {
  // 把 resolve 拿出來,調(diào)用,這樣 wait 就完成了,可以往下面執(zhí)行了
  const resolveHandler = this.list.shift()!;
  resolveHandler();
 }
 }
}

const run = async () => {
 const concurrent = new Concurrent();
 startTime = Date.now();
 concurrent.add(timeout1);
 concurrent.add(timeout2);
 concurrent.add(timeout3);
 concurrent.add(timeout4);
 concurrent.add(timeout5);
};

run();

At 300 return 2
At 700 return 3
At 1000 return 1
At 1200 return 5
At 1200 return 4

總結(jié)

這兩種方式都可以實現(xiàn)并發(fā)控制,只不過實現(xiàn)的方式不太一樣,主要都是靠 Promise 實現(xiàn),另外實現(xiàn)方式里面沒有考慮異常的情況,這個可以自己加上

到此這篇關(guān)于JavaScript/TypeScript 實現(xiàn)并發(fā)請求控制的示例代碼的文章就介紹到這了,更多相關(guān)JavaScript 并發(fā)請求控制內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論