[英]how to force execution of requests inside async.each with nodejs?
I have a async.each that iterates an array and for every element inside the array it execute a function "check" that has a request inside. 我有一个async.each迭代一个数组,对于数组中的每个元素,它执行一个函数“check”,里面有一个请求。 This is the code but when I run it I see from the debugger that node doesn't execute the check function and it block its execution. 这是代码,但是当我运行它时,我从调试器看到节点不执行检查功能并阻止其执行。
async.each(array,
function(v_page, callback){
if(v_page.url.length>=5){
internals.check(v_page.url,array2, function (body) {
callback();
});
}
},
function(err){
internals.calls(var1,var2,var3);
});
I tried with a normal for loop but it jump at the internals.calls function without execute the internals.check function for the async nature of node. 我尝试使用普通的for循环,但它跳转到internals.calls函数而不执行internals.check函数以获得节点的异步性质。 So how can i force the execution of the check function? 那么如何强制执行检查功能呢?
This is the code of the check function: 这是检查功能的代码:
internals.check = (url,array2,cb) => {
request(url, function(err, recordset) {
if(err){
cb(array2);
}else {
//some stuffs
cb(array2)
}
});
};
You call callback
only when v_page.url.length >= 5
, but you need to do that for each element: 只有当v_page.url.length >= 5
时才调用callback
,但是你需要为每个元素执行此操作:
async.each(array, function(v_page, callback) {
if(v_page.url.length >= 5) {
internals.check(v_page.url,array2, function(body) {
callback();
});
} else {
callback(); <== call callback here, when condition is not met
}
...
Another problem is that, you incorrectly call callback in internals.check
. 另一个问题是,您在internals.check
错误地调用了回调。 According Node.js notation, the first parameter of callback must be an error or null (async uses this notation). 根据Node.js表示法,回调的第一个参数必须是错误或null(异步使用此表示法)。 But in your case you call callback with array2
anyway: 但是在你的情况下你无论如何都用array2
调用回调:
internals.check = (url, array2, cb) => {
request(url, function(err, recordset) {
if (err) {
cb(err); // <== pass error here
} else {
cb(null, array2); // <== no error, so first parameter is null, the second is data
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.