我是node.js(和request.js)的新手。我想从具有不同路径的特定url中获取网站的主体(在下面的示例中http://www.example.com/path1,http://www.example.com/path2等),并将此数据记录在具有键/值映射的对象中(下面的siteData[path])。
var request = require('request'),
paths = ['path1','path2','path3'],
siteData = {},
pathLength = paths.length,
pathIndex = 0;
paths.forEach((path) => {
var url="http://www.example.com/"+path;
request(url, function(error, response, html){
if(!error){
siteData[path] = response.body;
pathIndex++;
if(pathIndex===pathLength){
someFunction(siteData);
}
}
});
function someFunction(data){
//manipulate data
}
我的问题是:
- if语句(index===length)看起来不是确定异步请求是否完成的正确方法。我应该如何正确检查请求是否已完成
- 当我执行上面的代码时,我得到了一个错误
(node) warning: possible EventEmitter memory leak detected. 11 unpipe listeners added. Use emitter.setMaxListeners() to increase limit.
,我尝试链接request(url, function(...){}).setMaxListeners(100);
,但没有成功
谢谢你的帮助!
看起来Promises是在这里完成任务的正确工具。我们将创建一个新的Promise
对象,而不是回调,该对象将在作业完成时解析。我们可以用.then
操作符说"一旦你完成了,就做更多的事情"
var rp = require('request-promise');
rp('http://www.google.com')
.then((htmlString) => {
// Process html...
});
(如果出现任何错误,promise将拒绝并直接进入.catch
)
someFunctionThatErrors('Yikes!')
.then((data) => {
// won't be called
})
.catch((err) => {
// Will be called, we handle the error here
});
我们有很多异步任务要做,所以仅仅一个承诺是行不通的。一种选择是将它们串联在一起,就像这样:
rp('http://www.google.com')
.then((htmlString) => rp('http://someOtherUrl.com'))
.then((otherHtmlString) => {
// and so forth...
但这失去了异步的一些可怕之处——我们可以在并行中完成所有这些任务。
var myRequests = [];
myRequests.push(rp('http://www.google.com').then(processStuff).catch(handleErr));
myRequests.push(rp('http://someOtherUrl.com').then(processStuff).catch(handleErr));
那个男孩看起来很丑。有一个更好的方法来处理所有这些-Promise.all()
(您使用的是箭头函数,所以我认为原生Promise
也适用于您)。它接受一个promise数组,并返回一个promises,该promises在数组的所有promise都已执行完毕时解析。(如果其中任何一个出现错误,它会立即拒绝)。.then
函数将被赋予一个数组,表示每个promise解析为的值。
var myRequests = [];
myRequests.push(rp('http://www.google.com'));
myRequests.push(rp('http://someOtherUrl.com'));
Promise.all(myRequests)
.then((arrayOfHtml) => {
// arrayOfHtml[0] is the results from google,
// arrayOfHtml[1] is the results from someOtherUrl
// ...etc
arrayOfHtml.forEach(processStuff);
})
.catch(/* handle error */);
尽管如此,对于我们想要点击的每个链接,我们都必须手动调用.push
。那不行!让我们使用Array.prototype.map
来实现一个巧妙的技巧,它将迭代我们的数组,依次操作每个值,并返回一个由新值组成的新数组:
var arrayOfPromises = paths.map((path) => rp(`http://www.example.com/${path}`));
Promise.all(arrayOfPromises)
.then((arrayOfHtml) => arrayOfHtml.forEach(processStuff))
.catch(function (err) { console.log('agh!'); });
更干净、更容易处理错误。
根据我的经验,在处理请求模块时,不能只使用forEach或任何类型的循环,因为它是异步执行的,最终会导致EventEmitter内存泄漏。
我解决这个问题的方法是使用递归函数。你可以参考下面的代码:
var request = require('request'),
paths = ['path1','path2','path3'],
siteData = {};
function requestSiteData(paths) {
if (paths.length) {
var path = paths.shift();
var url = "http://www.example.com/" + path;
request(url, function(error, response, html) {
if(!error) {
siteData[path] = response.body;
} //add else block if want to terminate when error occur
//continue to process data even if error occur
requestSiteData(paths); //call the same function
});
} else {
someFunction(siteData); //all paths are requested
}
}
function someFunction(data){
//manipulate data
}
requestSiteData(paths); //start requesting data
由于nodejs中request
方法的异步性,您无法直接知道它们的响应并实时采取行动。您必须等待回调到达,然后只有您才能调用下一个request
方法。
在这种情况下,您正在调用forEach
循环中的所有request
方法,这意味着它们将被逐个调用,而无需等待先前的响应。
我建议使用出色的async
库,如下所示-
var async = require('aysnc');
var request = require('request'),
paths = ['path1','path2','path3'],
siteData = {},
pathLength = paths.length,
pathIndex = 0,
count = 0;
async.whilst(
function () { return count < pathLength; },
function (callback) {
// do your request call here
var path = paths[pathLength];
var url="http://www.example.com/"+path;
request(url, function(error, response, html){
if(!error){
siteData[path] = response.body;
// call another request method
count++;
callback();
}
});
},
function (err) {
// all the request calls are finished or an error occurred
// manipulate data here
someFunction(siteData);
}
);
希望这能有所帮助。
我同意上面的解决方案,在这种情况下,承诺可能是可行的;然而,您也可以使用回调来实现同样的目的。
lodash库提供了跟踪完成了多少异步调用的方便方法。
'use strict';
var _ = require('lodash');
var path = require('path');
var paths = ['a', 'b', 'c'];
var base = 'www.example.com';
var done = _.after(paths.length, completeAfterDone);
_.forEach(paths, function(part) {
var url = path.join(base, part);
asynchFunction(url, function() {
done();
});
});
function completeAfterDone() {
console.log('Process Complete');
}
function asynchFunction(input, cb) {
setTimeout(function() {
console.log(input);
cb();
}, Math.random() * 5000);
};
使用此方法,done函数将跟踪完成了多少请求,并在加载每个url后调用最终回调。