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

异步并行请求按顺序运行

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

异步并行请求按顺序运行

您已经发现,

async.parallel()
只能并行化本身是异步的操作。如果操作是同步的,则由于node.js具有单线程特性,因此这些操作将一个接一个地运行,而不是并行运行。但是,如果操作本身是异步的,则
async.parallel()
(或其他异步方法)将立即启动所有操作并为您协调结果。

这是使用的一般思路

async.map()
。我
async.map()
之所以使用它,是因为这样的想法是,它将一个数组作为输入并以与原始数组相同的顺序生成一个结果数组,但是并行运行所有请求,这似乎与您想要的内容一致:

var async = require("async");var request = require("request");// create list of URLsvar lookup_list = [];for (var i = 0; i < 20; i++) {    var index = Math.round(Math.random() * 495) + 1;    var url = 'http://localhost:3001/generate?file=' + index;    lookup_list.push(url);}async.map(lookup_list, function(url, callback) {    // iterator function    request(url, function (error, response, body) {        if (!error && response.statusCode == 200) { var body = JSON.parse(body); // do any further processing of the data here callback(null, body);        } else { callback(error || response.statusCode);        }    });}, function(err, results) {    // completion function    if (!err) {        // process all results in the array here        console.log(results);        for (var i = 0; i < results.length; i++) { // do something with results[i]        }    } else {        // handle error here    }});

而且,这是一个使用Bluebird Promise的版本,并且有点类似地

Promise.map()
用于迭代初始数组:

var Promise = require("bluebird");var request = Promise.promisifyAll(require("request"), {multiArgs: true});// create list of URLsvar lookup_list = [];for (var i = 0; i < 20; i++) {    var index = Math.round(Math.random() * 495) + 1;    var url = 'http://localhost:3001/generate?file=' + index;    lookup_list.push(url);}Promise.map(lookup_list, function(url) {    return request.getAsync(url).spread(function(response, body) {        if response.statusCode !== 200) { throw response.statusCode;        }        return JSON.parse(body);    });}).then(function(results) {    console.log(results);    for (var i = 0; i < results.length; i++) {        // process results[i] here    }}, function(err) {    // process error here});


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

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

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