首页 > 解决方案 > 存储在回调函数外部范围内的对象中的值

问题描述

我有以下功能:

function exec(command) {
    const stdout = {
        command: null,
        output: null
    };
    stdout.command = command;
    chproc.exec(command, (error, out, stderr) => {
        if (error || stderr) {
            console.error(error || stderr);
            return;
        }
        temp = out;
    });
    stdout.output = temp;
    return stdout;

在哪里const chproc = require('child_process'); ,我一直试图将输出存储在chproc.exec对象中的回调函数中stdout,但它只在回调函数的范围内这样做,而不是在exec返回 null 的外部函数范围内。问题是,如果stdout它在全局范围内,并且我在 Node.js 终端中编写每个代码行 - 如果我运行文件,由于某种原因这也不起作用 - 所以如你所见,我是在混乱的混乱中,如果有人可以帮助清理它,非常感谢。

标签: javascriptnode.jsfunctionscope

解决方案


chproc.exec 接受 command 和一个 callback ,当 exec 完成调用时调用。因此,如果您将其包装在自己的函数中,那么我建议您保留相同的函数签名。

function exec(command, callback) {
    const stdout = {
        command: null,
        output: null
    };
    stdout.command = command;
    let temp;
    chproc.exec(command, (error, out, stderr) => {
        if (error || stderr) {
            console.error(error || stderr);
            return;
        }
        callback(out);
    });
    return stdout;
}

exec('ls', function (output) {
    console.log(output);
});

推荐阅读