我正在使用npm'powershell'包執行PowerShell命令並讀取相關輸出。我想寫一個函數來返回標準的命令輸出(這樣我可以調用該函數並在斷言中使用它的返回值等)。JavaScript - 從匿名函數參數返回值
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");
});
};
我想myFunction
返回數據值(從標準輸出)。但是,我不知道如何正確地做到這一點。您能否提一些建議?
通過網站上的節點'異步功能的異步函數返回值的一打':tl; dr - >使用回調或Promise – paqash
[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response -from-an-asynchronous-call) – paqash
'Promisify'你的函數或傳入'callback'。 有很多關於如何做到這一點的現有資源。 – Sachin