如何将Promise.all()限制为每秒5个承诺?

时间:2018-12-27 16:47:57

标签: javascript node.js promise es6-promise throttling

我有几个项目需要查询第三方API,并且所述API的呼叫限制为每秒5个调用。我需要以某种方式将对API的调用限制为每秒最多5个调用。

到目前为止,我仅在一组诺言上使用Promise.all(),每个诺言都会向API发送请求,并在API用HTTP状态代码200响应时解析,并在API响应时拒绝。响应其他状态代码。但是,当数组中有5个以上的项目时,我会冒Promise.all()被拒绝的风险。

如何将Promise.all()呼叫限制为每秒5个呼叫?

6 个答案:

答案 0 :(得分:2)

我希望这会对您有所帮助。

也可以说这将使用Promise.all来解决所有请求,如果您有大量查询,这将等待所有请求解决,并且可能导致代码中等待很多时间以获得所有响应。 而且,如果其中一个请求被拒绝,Promise.all也将拒绝。

我建议,如果不需要全部结果,最好使用lodash debouncethrottle之类的东西或处理此问题的框架。

let items = [
    {name: 'item1'}, 
    {name: 'item2'}, 
    {name: 'item3'}, 
    {name: 'item4'}, 
    {name: 'item5'}, 
    {name: 'item6'}
];

// This is the api request that you send and return a promise
function apiCall(item) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(item.name), 1000);
  })
}

new Promise((resolve) => {
  let results = [];

  function sendReq (itemsList, iterate, apiCall) {
    setTimeout(() => {
      // slice itemsList to send request according to the api limit
      let slicedArray = itemsList.slice(iterate * 5, (iterate * 5 + 5));
      result = slicedArray.map(item => apiCall(item));
      results = [...results, ...result];

      // This will resolve the promise when reaches to the last iteration
      if (iterate === Math.ceil(items.length / 5) - 1) {
          resolve(results);
      }
    }, (1000 * iterate)); // every 1000ms runs (api limit of one second)
  }

  // This will make iteration to split array (requests) to chunks of five items 
  for (i = 0; i < Math.ceil(items.length / 5); i++) {
    sendReq(items, i, apiCall);
  }
}).then(Promise.all.bind(Promise)).then(console.log);
// Use Promise.all to wait for all requests to resolve
// To use it this way binding is required

答案 1 :(得分:2)

如果您不太担心顺序解决承诺,则可以在bluebird中使用并发选项。

以下仅一次处理5个查询。

const Promise = require('bluebird');

const buildQueries = (count) => {
  let queries = [];

  for(let i = 0; i < count; i++) {
    queries.push({user: i});
  };

  return queries;
};

const apiCall = (item) => {
  return new Promise(async (resolve, reject) => {
    await Promise.delay(1000);
    resolve(item.user);
  });
};

const queries = buildQueries(20);

Promise.map(queries, async query => {
  console.log( await apiCall(query) );
}, {concurrency: 5});

答案 2 :(得分:0)

使用没有库的ES6

export async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}
export function split(arr, n) {
  var res = [];
  while (arr.length) {
    res.push(arr.splice(0, n));
  }
  return res;
}
export const delayMS = (t = 200) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(t);
    }, t);
  });
};
export const throttledPromises = (
  asyncFunction,
  items = [],
  batchSize = 1,
  delay = 0
) => {
  return new Promise(async (resolve, reject) => {
    const output = [];
    const batches= split(items, batchSize);
    await asyncForEach(batches, async (batch) => {
      const promises = batch.map(asyncFunction).map(p => p.catch(reject));
      const results = await Promise.all(promises);
      output.push(...results);
      await delayMS(delay);
    });
    resolve(output);
  });
};

答案 3 :(得分:0)

我认为您可以将您的问题分解为两个:一次不超过5个呼叫,并确保最新的呼叫要等到最早的1秒钟后才会发生。

第一部分易于使用令人惊叹的p-limit库来解决-到目前为止,它具有我见过的最简单的界面。

对于第二部分,您需要实际跟踪每个调用的开始时间-即实现一个等待功能: 基本的伪代码,尚未测试:

import pLimit from 'p-limit';
const apiLimit = pLimit(5);

const startTimes = [];

async function rateLimiter(item) {
  const lastSecond = (new Date().getTime()) - 1000;
  if (startTimes.filter(v => v > lastSecond).length >= 5) {
    await new Promise(r => setTimeout(r, 1000));
  }
  // TODO: cleanup startTimes to avoid memory leak
  startTimes.push(new Date().getTime());
  return apiCall(item);
}

await Promise.all(items.map(v => apiLimit(() => rateLimiter(v))))

答案 4 :(得分:0)

我们可以使用生成器来发送一个组中的承诺列表。 一旦解决了第一个收益,我们就可以做另一个收益。 我们将结果存储在一个数组中。 一旦 promiseArray 长度等于结果长度,我们就可以解析 包装承诺。

const fetch = require("isomorphic-fetch");
const totalPromiseLength = 5;
const requestMethod = url => () => fetch(url).then(response => response.json());
let promiseArray = [...new Array(totalPromiseLength).keys()].map(index =>
  requestMethod("https://jsonplaceholder.typicode.com/todos/" + (index + 1))
);
function* chunks(arr, limit) {
  for (let i = 0; i < Math.ceil(arr.length / limit); ++i) {
    yield [...arr].slice(i * limit, i * limit + limit);
  }
}

new Promise(async resolve => {
  let generated = chunks(promiseArray, 2);
  let result = [];
  for (let bla of generated) {
    await Promise.all(bla.map(param => param())).then(response => {
      result = [...result, ...response];
      if (result.length === promiseArray.length) {
        resolve(result);
      }
    });
  }
}).then(response => {
  console.log(response);
});

答案 5 :(得分:0)

也许我头脑简单,但我写的这个版本只是将传入的数组分成 5 个承诺块,并在每个块上执行 Promise.all() :

utility.throttledPromiseAll = async (promises) => {
  const MAX_IN_PROCESS = 5;
  const results = new Array(promises.length);

  async function doBlock(startIndex) {
    // Shallow-copy a block of promises to work on
    const currBlock = promises.slice(startIndex, startIndex + MAX_IN_PROCESS);
    // Await the completion. If any fail, it will throw and that's good.
    const blockResults = await Promise.all(currBlock);
    // Assuming all succeeded, copy the results into the results array
    for (let ix = 0; ix < blockResults.length; ix++) {
      results[ix + startIndex] = blockResults[ix];
    }
  }

  for (let iBlock = 0; iBlock < promises.length; iBlock += MAX_IN_PROCESS) {
    await doBlock(iBlock);
  }
  return results;
};