【问题标题】:A value stored in an object dumbed in the outer scope of a callback function [duplicate]存储在回调函数外部范围内的对象中的值[重复]
【发布时间】:2020-11-02 11:07:45
【问题描述】:

我有以下功能:

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 终端中编写每个代码行 - 如果我运行该文件,这也因某种原因不起作用 - 如你所见,我陷入了混乱,如果有人可以帮助清理它,不胜感激。

【问题讨论】:

    标签: javascript node.js function scope


    【解决方案1】:

    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);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      相关资源
      最近更新 更多