我正在使用该async.eachLimit功能一次控制最大操作数.
const { eachLimit } = require("async");
function myFunction() {
return new Promise(async (resolve, reject) => {
eachLimit((await getAsyncArray), 500, (item, callback) => {
// do other things that use native promises.
}, (error) => {
if (error) return reject(error);
// resolve here passing the next value.
});
});
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我无法将该myFunction函数声明为异步,因为我无法访问eachLimit函数的第二个回调内的值.
我在Node.js下使用Bluebird promise库,这太棒了!但我有一个问题:
如果你看一下Node的child_process.exec和child_process.execFile的文档,你会发现这两个函数都返回了一个ChildProcess对象.
那么推荐这种功能的方法是什么?
请注意以下工作(我得到一个Promise对象):
var Promise = require('bluebird');
var execAsync = Promise.promisify(require('child_process').exec);
var execFileAsync = Promise.promisify(require('child_process').execFile);
Run Code Online (Sandbox Code Playgroud)
但是如何才能访问原始Node.js函数的原始返回值?(在这些情况下,我需要能够访问最初返回的ChildProcess对象.)
任何建议将不胜感激!
编辑:
下面是一个使用child_process.exec函数返回值的示例代码:
var exec = require('child_process').exec;
var child = exec('node ./commands/server.js');
child.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
child.stderr.on('data', function(data) {
console.log('stderr: ' + data);
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我将使用exec函数的promisified版本(上面的execAsync),那么返回值将是一个promise,而不是ChildProcess对象.这是我正在谈论的真正问题.
请考虑这段代码:
var cmd = `cd "${dir}" && curl -L "${url}" | tar -xJvf - | zip -qr archive.zip -@`;
await exec(cmd);
res.sendFile(path.join(dir, "archive.zip"));
Run Code Online (Sandbox Code Playgroud)
它下载一个 .tar.xz,解压并重新压缩,最后发送给用户。
如果我运行它,它不会res.sendFile(...)说该文件不存在。但是,如果我查看我的文件系统,zip 文件实际上就在那里。
所以我尝试在之前添加一个小的延迟res.sendFile(...),如下所示:
var cmd = `cd "${dir}" && curl -L "${url}" | tar -xJvf - | zip -qr archive.zip -@`;
await exec(cmd);
setTimeout(()=>{
res.contentType(path.join(dir, "archive.zip"));
res.sendFile(path.join(dir, "archive.zip"));
}, 1000);
Run Code Online (Sandbox Code Playgroud)
...它神奇地起作用了。
似乎exec(cmd)实际上并没有等待命令完成。是因为它是管道吗?