简体   繁体   中英

Simplify node V8 childprocess.exec

I had a very clean simple way of doing "await runJob()" using Node V8 Promisfy() and async functions. The issue I have is that I needed a handle to the child object returned by childProcess.execFile(). So now I have a very messy solution that works... but I am obviously not happy with it. Any ideas on how to clean this up?

Before:

const invoke = util.promisify(childProcess.execFile)

async runJob() {
    try {
        const std = await invoke(this.FMEPath, ["PARAMETER_FILE", this.fmeParamFile], { cwd: this.root })
        this.stderr = std.stderr
        this.stdout = std.stdout
    } catch (err) {
        this.errors++
        logger.addLog('error', "FMEjob.runJob - childProcess.execFile failed: %s", err.message, { paramFile: this.fmeParamFile, error: err })
    }
}

After:

 async runJob() {
    return new Promise((resolve, reject) => {
        this.child = execFile(this.FMEPath,
            ["PARAMETER_FILE", this.fmeParamFile],
            { cwd: this.root },
            (err, stdout) => {
                if (err) {
                    this.errors++
                    logger.addLog('error', "FMEjob.runJob - childProcess.execFile failed: %s", err.message, { paramFile: this.fmeParamFile, error: err })
                    return reject(false)
                } else {
                    this.stderr = stderr
                    this.stdout = stdout
                    resolve(true)
                }
            })
    })
}

Put only the resolve / reject inside the callback and nothing else:

async runJob() {
    try {
        const std = await new Promise((resolve, reject) => {
            this.child = execFile(this.FMEPath, ["PARAMETER_FILE", this.fmeParamFile], { cwd: this.root }, (err, std) => {
                if (err) reject(err);
                else resolve(std);
            });
        });
        this.stderr = std.stderr
        this.stdout = std.stdout
        return true;
    } catch (err) {
        this.errors++
        logger.addLog('error', "FMEjob.runJob - childProcess.execFile failed: %s", err.message, { paramFile: this.fmeParamFile, error: err })
        throw false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM