javascript - 存储在回调函数外部范围内的对象中的值
问题描述
我有以下功能:
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 终端中编写每个代码行 - 如果我运行文件,由于某种原因这也不起作用 - 所以如你所见,我是在混乱的混乱中,如果有人可以帮助清理它,非常感谢。
解决方案
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);
});
推荐阅读
- java - 寻找与 quarkus 共享微服务之间接口的最佳方式
- wordpress - 搜索插件破坏部分主题
- java - 如何更改服务运行通知标题、图像和描述?
- node.js - 客户端不显示Flash消息,如何解决?
- python-3.x - Conda 环境包括来自不同环境的包
- javascript - 部署到 Heroku 失败(React/Node monorepo)
- vue.js - fusioncharts在重新加载时出现渲染错误
- c++ - 隐式 const/nonconst 运算符 bool
- hpc - qsub -t 工作“已死”
- flutter - MissingPluginException(在通道 plugins.flutter.io/image_picker 上找不到方法 pickImage 的实现)