站点工具

用户工具


字节跳动面试题:用JS实现Ajax并发请求控制

实现方法有多种,这里参考一个async-pool的库,https://github.com/rxaviers/async-pool/blob/master/lib/es6.js 。代码很短很精华

//https://github.com/rxaviers/async-pool/blob/master/lib/es6.js
 
async function asyncPool(limit, array, iteratorFn) {
  const ret = [];
  const executing = [];
  for (const item of array) {
    const p = iteratorFn(item); 
    ret.push(p);
    if (limit <= array.length) {
      const e = p.then(() => { 
        console.log('正在运行' + executing.length)
        executing.splice(executing.indexOf(e), 1)
      });
      executing.push(e);
      if (executing.length >= limit) {
        await Promise.race(executing);
      }
    }
  }
  return Promise.all(ret);
}
 
 
 
 
const timeout = (i) => {
  console.log('开始' + i);
 
  return new Promise((resolve) => setTimeout(() => {
    resolve(i);
    console.log('结束' + i);
  }, 1000+Math.random()*1000));
};
 
let urls = Array(10).fill(0).map((v,i)=>i)
console.log(urls);
(async () => {
    const res = await asyncPool(3, urls, timeout);
    console.log(res);
 })()
若愚 · 2021/12/01 20:13 · javascript_并发.txt