栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

运行1000个请求,以便一次仅运行10个

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

运行1000个请求,以便一次仅运行10个

有很多方法可以处理一次运行的10个请求。

  1. 异步库 -将异步库与

    .parallelLimit()
    方法一起使用,您可以在其中指定要一次运行的请求数。

  2. Bluebird Promise库 -使用 Bluebird Promise 库和该

    request
    库将您的
    http.get()
    东西包装成可以返回 Promise的 东西,然后将
    Promise.map()
    并发选项设置为
    10

  3. 手动编码 - 手动编码 您的请求以启动10个请求,然后每次完成一个请求,再启动另一个请求。

在所有情况下,您都必须手动编写一些重试代码,并且与所有重试代码一样,您将必须非常仔细地确定重试错误的类型,重试错误的时间,重试尝试之间的间隔以及何时重试。最终放弃(您未指定的所有内容)。

我首选的方法是使用Bluebird和promises。依次包括重试和结果收集,可能看起来像这样:

const request = require('request');const Promise = require('bluebird');const get = Promise.promisify(request.get);let remoteUrls = [...];    // large array of URLsconst maxRetryCnt = 3;const retryDelay = 500;Promise.map(remoteUrls, function(url) {    let retryCnt = 0;    function run() {        return get(url).then(function(result) { // do whatever you want with the result here return result;        }).catch(function(err) { // decide what your retry strategy is here // catch all errors here so other URLs continue to execute if (err is of retry type && retryCnt < maxRetryCnt) {     ++retryCnt;     // try again after a short delay     // chain onto previous promise so Promise.map() is still     // respecting our concurrency value     return Promise.delay(retryDelay).then(run); } // make value be null if no retries succeeded return null;        });    }    return run();}, {concurrency: 10}).then(function(allResults) {     // everything done here and allResults contains results with null for err URLs});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484671.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号