简体   繁体   English

TypeScript - 在链式 function 中传递参数

[英]TypeScript - Passing parameter in chained function

In node.js I'm making call a script with exec from child_process .在 node.js 中,我正在使用来自child_processexec调用脚本。

When in the closed state I want to check if there was any error so I can return it however I can't seem to access error in the second function on() .当在封闭的 state 中时,我想检查是否有任何错误,以便我可以返回它但是我似乎无法访问第二个 function on()中的error

Could someone kindly explain how I can pass it along.有人可以解释一下我如何传递它。

exec('myScript.sh',
        (error: any, stdout: any, stderr: any) => { }).on('close', () => {
            console.log(error)
        })

Thanks.谢谢。

You need to store it outside of the callback function.您需要将其存储在回调 function 之外。 If you look at the ES5 equivalent:如果您查看 ES5 等效项:

exec("myScript.sh", function(error, stdout, stderr) {
    // Do nothing
}).on("close", function() {
    // Cannot access error here
});

You can see that the scope of error is local to the anonymous callback function that is exec 's second argument.您可以看到error的 scope 是exec的第二个参数的匿名回调 function 的本地。 You can access it within the onclose callback function by storing it with a scope accessible to that function like so:您可以在 onclose 回调 function 中访问它,方法是将其与 function 可访问的 scope 一起存储,如下所示:

let execError = "";

exec("myScript.sh", function(error, stdout, stderr) {
    execError = error;
}).on("close", function() {
    console.log(execError);
});

Or in your original notation (ES6):或者在您的原始符号(ES6)中:

let execError: any = "";

exec("myScript.sh", (error: any, stdout: any, stderr: any) => { 
    execError = error; 
}).on("close", () => { 
    console.log(execError); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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