Nodejs识别asyntasks的输出
我是nodejs的新手,我使用请求nodejs api发出多个get请求,用这个,我无法弄清楚某个特定请求的输出。 如何分别识别每个请求的响应? 我正在使用for循环发送多个请求。 如果我使用recursion,它再次成为同步,我只需要分开请求与响应太asynchronous。 可能吗 ?
在下面的代码中,variables'i'被上次迭代replace。
var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mobiles%20with%20best&phrase2=Mobiles%20with%20best', 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%2520Mobiles%2520with%2520best&phrase2=what%20is%20a%20processor'] function ss(list){ for(var i in list) { request(list[i], function (error, response, body) { if (!error && response.statusCode == 200) { console.log( i + " " +body); } }) } }
您可以使用asynchronous库来执行asynchronous请求。 具体来说,您可以使用async.each
或async.eachSeries
。
它们之间的区别在于它们each
都会并行地运行所有的请求,就像for
循环一样,但是会保留上下文,而不是eachSeries
将一次运行一个请求的系列(第二次迭代将只在你调用了第一个callback函数)。 另外 – 还有更多特定用例的其他选项(比如eachLimit
)。
示例代码使用each
:
var list = [ 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%20Mobiles%20with%20best&phrase2=Mobiles%20with%20best', 'http://swoogle.umbc.edu/SimService/GetSimilarity?operation=api&phrase1=%2520Mobiles%2520with%2520best&phrase2=what%20is%20a%20processor'] function ss(list){ async.each(list, function(listItem, next) { request(listItem, function (error, response, body) { if (!error && response.statusCode == 200) { console.log( listItem + " " +body); } next(); return; }) }, //finally mehtod function(err) { console.log('all iterations completed.') }) }