【发布时间】:2021-03-26 19:33:44
【问题描述】:
我想通过 SSH 在服务器上连续运行多个功能,一个接一个。我可以为此使用 await/async 函数,但无法让这个示例工作:记录一些文本,运行 uptime(等待完成),记录更多文本。
我应该看到输出:
Before await function
STDOUT: (all the uptime info here)
Uptime completed successfully.
After await function
但现在我明白了:
Before await function
After await function
STDOUT: (all the uptime info here)
Uptime completed successfully.
函数 mainFunction 不应在函数完成之前打印两个控制台日志。
这是我的例子:
const Client = require('ssh2').Client;
const conn = new Client();
function uptimeFunction() {
conn.on('ready', function() {
conn.exec('uptime', function(err, stream) {
if (err) throw err;
stream.on('close', function(code, signal) {
conn.end();
if (code === 0) {
console.log('Uptime completed successfully.');
}
}).on('data', function(data) {
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
});
});
conn.connect(staging);
};
function awaitFunction() {
return new Promise((resolve, reject) => {
resolve(uptimeFunction());
});
}
async function mainFunction() {
console.log('Before await function');
await awaitFunction();
console.log('After await function');
}
mainFunction();
我已经研究过“ssh2-promise”,但我不明白“exec”的示例会有所帮助。如果我确实需要使用 ssh2-promise,那么这个示例会如何?
是我做错了什么,还是 await 无法像我想象的那样通过 SSH 工作?
谢谢!
【问题讨论】:
-
看起来在
awaitFunction中,你立即用uptimeFunction的返回值解决了promise,这不是异步的。 -
知道了。此外,我更新了我的问题以根据需要从
awaitFunction中删除异步。感谢您的建议!
标签: javascript node.js asynchronous async-await promise