如何在Node.js中添加延迟

时间:2019-02-02 10:36:18

标签: node.js

我打电话循环第三方API在我的应用程序的NodeJS。基本上,我有一个列表,正在列表中进行迭代并调用第三方API。 第三方API速度很慢,不能处理3个以上的请求。建议我增加一些延迟。 请有人建议在这种情况下如何增加延迟。

    var promises = [];
    promises = rids.map((rid,j) => {
        // 3rd party API
        // getServiceDetailsApi is wrapper around 3rd party API
        return getServiceDetailsApi(rid)
    });
    // console.log(promises);
    Promise.all(promises)
    .then(res => {
        // console.log('promise complete..' + res.length)

        var responses = [];
        res.map((response,i) => {
            var serviceAttributesDetail = {};
            // console.log(response);
            serviceAttributesDetails = response.data.serviceAttributesDetails;
            serviceAttributesDetail.rid = serviceAttributesDetails.rid;
            responses = responses.concat(serviceAttributesDetail);
        })
        // Add more logic above
        return Promise.all(responses); 
    })

2 个答案:

答案 0 :(得分:0)

如果一次请求足够了,您可以尝试以下方式:

'use strict';

(async function main() {
  try {
    const responses = [];
    for (const rid of rids) {
      const response = await getServiceDetailsApi(rid);
      responses.push({ rid: response.data.serviceAttributesDetails.rid });
    }
    console.log(responses);
  } catch (err) {
    console.error(err);
  }
})();

答案 1 :(得分:0)

如果您的限制是对该API最多有3个并发请求,则有一种可能性(不过,可能有错别字,但我不认为拒绝处理如此):

const cfgMaxApiCalls = 3;
...
function getServiceDetailsApi() {...}
...
const rids = ...
...
const promisedResponses = new Promise((generalResolve) => {
  let currentCalls = 0; // to know how many calls in progress
  const responses = []; // the output of the general promise
  // this chains promises, ensuring we do an API call only when another one finished
  const consumer = (response) => {
    responses.push(response); // first remember the data
    // stop condition: nothing more to process, and all current calls have resolved
    if (!rids.length && !currentCalls--) {
      return generalResolve(responses);
    }
    // otherwise make a new call since this one's done
    return getServiceDetailsApi(rids.shift()).then(consumer);
  };
  // start the process for maximum `cfgMaxApiCalls` concurrent calls
  for (; currentCalls < cfgMaxApiCalls && rids.length; currentCalls++) {
    getServiceDetailsApi(rids.shift()).then(consumer);
  }
});
promisedResponses.then((res) => {
  // here `res` === your code's `res`
  // and by the way, Array.prototype.concat is not asynchronous,
  // so no need to Promise.all(responses) at the end ;)
});