我有一个包含一些 ID 的数组,例如 a = [abc,cde,efg]
。我将这个数组和第二个包含适合 ID 的名称的数组传递给 Node 中的子进程。
我想等到子进程完成并处理下一个数组成员。
实现它的代码是(使用建议的编辑):
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 脚本内执行的curl 请求。 shell 脚本可以正常工作,不会出现错误。现在,由于 async.eachOfLimit
限制,该脚本仅被调用两次。那么其他的数组ID就不再处理了。
编辑
这是我最后尝试过的代码,但是随后会调用所有可能的网址,而不是仅 2 个。我在这里找到了这个 Another Stackoverflow question 。我也尝试过 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
关于node.js - Node 子进程 exec async 仅调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841232/