简体   繁体   中英

JavaScript - returning value from anonymous function parameter

I am using npm 'powershell' package for executing PowerShell commands and reading related output. I want to write a function that would return standard command output (so that I could call the the function and use its return value in assertions etc.).

const PowerShell = require("powershell");

var myFunction = function (command) {
    let ps = new PowerShell(command);

    ps.on("error", err => {
        console.error(err);
    });

    ps.on("output", data => {
        console.log(data);
        //return data; <-- this does not work
    });

    ps.on("error-output", data => {
        console.error(data);
    });

    ps.on("end", code => {
        console.log("The end");
    });
};

I want myFunction to return data value (from standard output). However, I don't know how to do it properly. Could you please advise?

Look into how callbacks work. An example for your function would be

var myFunction = function (command, callback) {
    // code
    ps.on("output", data => {
        callback(data)
    });
    // code
};

myFunction('ls', function (data) {
    console.log('The callback data:', data);
});

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