我有一个这样的函数,它接受命令,参数并产生一个过程:
execPromise (command, args) {
return new Promise((resolve, reject) => {
const child = spawn(command, args)
child.stdout.on('data', (data) => {
this.logger.info(`stdout: ${data}`)
})
child.stderr.on('data', (data) => {
this.logger.info(`stderr: ${data}`)
})
child.on('close', (code) => {
if (code !== 0)
this.logger.error(`Command execution failed with code: ${code}`)
else
this.logger.info(`Command execution completed with code: ${code}`)
resolve()
})
})
}
Promise让它等到过程结束。
我想要的是用async / await构造替换Promise。
当我只等spawn
时:
async execPromise (command, args) {
const child = await spawn(command, args)
...
}
execPromise
不会等到流程结束并继续工作。
有没有办法重构此代码以使用async / await?
答案 0 :(得分:6)
如spawn documentation所述,该功能的工作方式如下:
运行ls -lh / usr,捕获stdout,stderr和exit的示例 代码:
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
我们在此理解,为了使用spawn
,您必须倾听events
data
和close
。
你问的是:
我们是否可以使用spawn
模式直接调用async/await
函数?
答案:
是的,你可以拥有它,但你必须自己做。您创建execPromise
的方式现在可以await execPromise(...)
。
要明确,spawn
函数不能直接绑定到async/await
。 await
需要Promise
个对象等待,spawn
不会返回Promise
个对象。