如何回傳下面的 getData 函式的值(資料)?
const { Client } = require('ssh2');
const conn = new Client();
function getData() {
//i tried to assign the data to a variable but failed
//var rawData = '';
conn.on('ready', () => {
conn.exec('pwd', (err,stream)=>{
if (err) throw err;
stream.on('data',(data)=>{
//the console successfully displayed - the current path
console.log('Output:' data);
//if i return the data here the output was undefined
//return data
});
stream.stderr.on('data',(data)=>{
});
stream.on('close',(code,signal)=>{
conn.end();
});
//if i tried to get the data values here, it threw "unhandled 'error' event", so i would not possible to return the data here.
//console.log(data);
});
}).connect({
host: 'myserver',
port: 22,
username: 'root',
password: 'roots!'
});
}
getData();
從內部流中安慰出來是成功的,但是如何回傳資料呢?我試圖將資料分配給變數(rawaData),但混淆了“回傳”代碼的放置位置。
uj5u.com熱心網友回復:
您可以使用承諾來傳達最終結果:
function getData() {
return new Promise((resolve, reject) => {
let allData = "";
conn.on('ready', () => {
conn.exec('pwd', (err, stream) => {
if (err) {
reject(err);
conn.end();
return;
}
stream.on('data', (data) => {
allData = data;
});
stream.on('close', (code, signal) => {
resolve(allData);
conn.end();
});
stream.on('error', reject);
});
}).connect({
host: 'myserver',
port: 22,
username: 'root',
password: 'roots!'
});
});
}
getData().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/438305.html
上一篇:從函式回傳值
下一篇:計算點之間的總距離
