如何用async / await等待child_process.spawn的执行?
我有一个这样的函数,它接受一个命令,参数和一个进程:
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() }) }) }
承诺让它等待,直到过程结束。
我想要的是用asynchronous/等待构造replace承诺。 当我只等待spawn
像:
async execPromise (command, args) { const child = await spawn(command, args) ... }
execPromise
不会等待进程完成并继续工作。
有没有什么办法来重构这段代码来处理asynchronous/等待?
正如spawn文档所描述的,该函数的工作原理如下:
运行ls -lh / usr,捕获stdout,stderr和退出代码的示例:
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
。
你问的是 :
我们可以有一个将被直接使用async/await
模式调用的spawn
函数吗?
答:
是的,你可以拥有它,但你必须自己动手。 您创buildexecPromise
的方式现在可以await execPromise(...)
。
要清楚的是, spawn
函数不能直接绑定到async/await
。 await
需要一个Promise
对象等待,并spawn
不返回一个Promise
对象。