[英]Can you help me understand how async await works in Node.js?
我正在嘗試在 Node 中為 hubot 編寫一個腳本,該腳本在遠程服務器上運行命令以獲取當前安裝在該服務器上的各種第三方軟件的當前版本。
我的問題是在我的 getVersions function 快結束時,它調用 getVersionsOverSSH function。 但是,版本數組在嘗試打印版本內容之前不會等待被調用的 function 完成。 我在 Node 方面不是很有經驗,所以我對 await/async 工作原理的理解是有限的。 有人可以告訴我如何以同步方式運行此腳本,以便在繼續之前等待 SSH function 完成嗎? 謝謝
獲取版本.js
versions = [];
async function getVersions(res) {
const env = getEnvsFromRequest(res.match[2].toString());
const resEnv = resolver.resolveEdiEnv(env);
if (resEnv === null) {
res.reply(`${env} is not in my list of available environments.`);
return;
}
if (resEnv.length > 0) {
response = response.concat(`\nHere are the results for ${resEnv}:\n`);
}
// Resolve hosts for environment
let resHosts = [];
resHosts = await resolver.resolveHosts(resEnv);
// Resolve creds for environment
let resCreds = [];
resCreds = await resolver.resolveCreds(resEnv);
try {
versions = await getVersionsOverSSH(resHosts,resCreds);
console.log(versions) // this line prints before array is loaded
} catch (err) {
console.log(err);
}
}
// function that makes the ssh calls and appends verions into an array
// returns array complete with versions from each command
function getVersionsOverSSH(resHosts,resCreds) {
dummy = [];
const ssh = new SSH({
host: resHosts[1],
user: resCreds[0],
pass: resCreds[1]
});
ssh
// Software 1 version
.exec('head -3 /app/foo/bar | tail -1 | cut -d \'=\' -f 2', {
out(stdout) { dummy.push(`Software 1 version: ${stdout}`); },
})
// Software 2 version
.exec('cd /app/foo/foo/bar && ls -td -- * | head -n 1', {
out(stdout) { dummy.push(`Software 2 version: ${stdout}`); },
})
// Software 3 Version
.exec(`cd /app/foo/bar/foo && ./version.sh | grep Foo* | cut -d \' \' -f 3`, {
out(stdout) { dummy.push(`Software 3: ${stdout}`); },
})
.start();
console.log(dummy); // this prints correctly
return dummy;
}
您需要返回 promise 並在需要時解決。 和 getVersionsOverSSH 里面execSync
function getVersionsOverSSH(resHosts,resCreds) {
return new Promise((resolve, reject) => {
dummy = [];
const ssh = new SSH({
host: resHosts[1],
user: resCreds[0],
pass: resCreds[1]
});
ssh
// Software 1 version
.execSync('head -3 /app/foo/bar | tail -1 | cut -d \'=\' -f 2', {
out(stdout) { dummy.push(`Software 1 version: ${stdout}`); },
})
// Software 2 version
.execSync('cd /app/foo/foo/bar && ls -td -- * | head -n 1', {
out(stdout) { dummy.push(`Software 2 version: ${stdout}`); },
})
// Software 3 Version
.execSync(`cd /app/foo/bar/foo && ./version.sh | grep Foo* | cut -d \' \' -f 3`, {
out(stdout) { dummy.push(`Software 3: ${stdout}`); },
})
.start();
console.log(dummy); // this prints correctly
//
resolve(dummy);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.