我有一个带有诸如 a = [abc,cde,efg]
之类的ID的数组。我将这个数组和第二个数组传递给了与iD的名称中的名称,以与节点中的子进程一起使用。我想等到孩子的过程完成,然后处理下一个数组成员。
实现它的代码是(使用建议的编辑(:
function downloadSentinel(promObj) {
return new Promise((resolve,reject) => {
function makeRequest(url, i, callback) {
url = promObj.ID;
name = promObj.Name;
var sys = require('util'),
exec = require('child_process').exec,
child;
var directory = __dirname.substring(0, __dirname.indexOf("\app_api"));
console.log(directory);
child = exec(directory + '\downloadProducts.sh' + promObj.ID[i] + ' ' + promObj.Name[i], function (error, stdout, stderr) {
child.on("error", function (error) {
console.log(error);
})
child.stdout.on('data', function (data) {
console.log(data.toString());
});
child.on('exit', function(exit) {
console.log(exit);
callback();
})
})
}
async.eachOfLimit(promObj.requestURLS, 2, makeRequest, function (err) {
if (err) reject(promObj)
else {
resolve(promObj);
}
});
});
}
我正在使用NPM-Async来控制并发流,因为我想限制我在Shell脚本中执行的卷曲请求。Shell Sript工作没有错误。现在,由于async.eachOfLimit
限制,该脚本仅被称为两次。然后其他数组ID不再处理。
编辑
这是我终于尝试过的代码,但是所有可能的URL都会被唤起,而不仅仅是2。我在这里找到了另一个stackoverflow问题。我还尝试了async.timeslimit
function downloadSentinel(promObj,req,res) {
async.eachOfLimit(promObj.requestURLS, 2,function (value,i,callback) {
console.log('I am here ' + i + 'times');
url = promObj.requestURLS;
name = promObj.Name;
console.log(promObj.requestURLS);
var sys = require('util'),
exec = require('child_process').exec,
child;
var directory = __dirname.substring(0, __dirname.indexOf("\app_api"));
console.log(directory);
console.log("executing:", directory + '\downloadProducts.sh ' + promObj.requestURLS[i] + ' ' + promObj.Name[i]);
child = exec(directory + '\downloadProducts.sh' + ' ' + promObj.requestURLS[i] + ' ' + promObj.Name[i], function (error, stdout, stderr) {
if (error != null){
console.log(error);
}
// this task is resolved
return callback(error, stdout);
});
}, function (err) {
if (err) console.log('error')
else {
console.log('Done');
}
});
}
我错过了什么?预先感谢。
exec
是异步的,它不在等待启动的过程完成。
将呼叫移至child.on('exit' ...)
处理程序内的callback()
或使用Execsync