实现 promise throttle | 刷题打卡

1,255 阅读1分钟

题目描述

image.png 题目地址

思路分析

这个题非常常见,市面上的解决方法也很多,之前一直用 状态机 解决,刷题中发现用 iterator 的操作非常秀,先贴出来然后慢慢分析

// 首先需要完成第一次Promise.all([fns * 5]);

function throttlePromises(fns, count) {
  const results = [];

  假如 count = 5;
  假如 fns = [async1, async2, ..., async100];
  把 fns 添加到 result,并且第一次只能添加5个
  result结果为
  const workers = Array(count).fill([...fns].entries()).map(iterator => {
    for (let [index, item] of iterator) {
      const result = await item();
      results[index] = result;
    }
  });
  return Promise.all(workers).then(() => results);
}

代码太短了,也正是这样让我眼前一亮,巧妙的运用 iterator 完成 promise节流
本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情