【问题标题】:NodeJS parallel running function to fetch data from an REST APINodeJS 并行运行函数从 REST API 获取数据
【发布时间】:2021-04-24 10:56:54
【问题描述】:

我一直在使用 Node.js 代码调用 API。我一次得到 50 个对象的分页响应。在查询参数中,我将偏移量设置为 0、50、100 以继续获取更多数据。如果响应有 50 个对象,我会增加我的偏移量查询参数。一旦数据少于 50,我就会停止通话。有什么方法可以拆分呼叫以更快地获取数据?假设我调用 api?offset=0api?offset=50api?offset=100api?offset=150 ,并行,以便我以更快的方式获取数据,并收集所有调用的数据。此外,如果没有数据停止调用下一个偏移值。 注意:我不知道偏移限制。

【问题讨论】:

    标签: node.js api rest


    【解决方案1】:

    使用递归函数

    由于您不知道偏移量限制是您对大量请求的最佳猜测,因此您将更快地达到您的偏移量。

    对于异步任务,我喜欢使用 async here。这是一个例子:

    const async = require('async')
    
    const offsets = [0, 50, 100, 150];
    async.map(offsets, function (offset, callback) {
      
      // Do request here with 'offset'
      // And return response in the callback
      // Do not return an error, otherwise the main callback (of map function)
      // will be called immediately
      return callback (null, response);
    
    }, function (error, results) {
    
      // results is an array containing all responses from all requests
      // iterate over results, if all contain a valid result, 
      // you can increase your offset group and perform this operation again
    
    });
    

    当然,您需要将其包装到另一个允许增加 offsetgroup 的函数中,只要您获得有效结果就重复请求 -> 所谓的 递归函数

    const async = require('async')
    
    function performGroupRequest (offsets, allResults, end) {
      
      async.map(offsets, function (offset, callback) {
      
        // Do request here with 'offset' and return response in the callback
        return callback (null, response);
    
      }, function (error, results) {
      
        // check results
        results.map(r => {
          if (hasItems(r)) {
            // valid result, add to allResults
            allResults.push(r);
          } else {
            // invalid result, let's end here
            return end(allResults);
          }
        });
    
        // all results are valid here, so call the function again, with increased offset
        performGroupRequest(offsets.map(o => o + 200), allResults, end)
    
      });
    }
    
    function getAllItems () {
      return Promise((resolve, reject) => {
      
        performGroupRequest([0, 50, 100, 150], [], function(all) {
          return resolve(all);
        });
      
      });
    }
    
    // start the journey
    
    getAllItems().then((allResults) => {
    });
    

    ? 请注意:为了简单起见,我在这里完全省略了错误处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多