[英]Javascript: Strange behavior when using promises, async-await, returns “Promise <pending>”
[英]Getting 'Promise { <pending> }' message when using async-await to perform tcp client
我正在使用telnet-client
節點模塊執行 tcp 客戶端。
const Telnet = require('telnet-client')
async function wazuhRun(host) {
let connection = new Telnet()
let ErrCode = -1;
let params = {
host: host,
port: 2345,
negotiationMandatory: false,
timeout: 1500
}
try {
await connection.connect(params)
ErrCode = 0;
} catch(error) {
ErrCode = -1;
}
return ErrCode;
}
const code = wazuhRun('linux345');
console.log(code);
在運行上述代碼時,我得到Promise { <pending> }
請建議我的代碼中可能缺少的內容
由於您在異步 function 之外使用它,因此您需要將其視為 Promise:
wazuhRun('linux345').then((result) => console.log(result));
異步函數是 Promises 周圍的語法糖,它們被翻譯成 Promises,這就是為什么你會得到 Promise 掛起。
如果您從另一個異步 function 內部調用它,您可以使用:
const code = await wazuhRun('linux345');
編輯:關於 null 返回,可能是您的 function 在您的 try/catch 之前引發錯誤。
wazuhRun('linux345')
.then((result) => console.log(result))
.catch((error) => console.log(error));
通過向 Promise 添加一個 catch 處理程序,您將能夠看到從異步 function 中拋出的所有錯誤。
使用 wazuhRun('linux345').then() 它將正常工作。
const Telnet = require('telnet-client')
async function wazuhRun(host) {
let connection = new Telnet()
let ErrCode = -1;
let params = {
host: host,
port: 2345,
negotiationMandatory: false,
timeout: 1500
}
try {
await connection.connect(params)
ErrCode = 0;
} catch(error) {
ErrCode = -1;
}
return ErrCode;
}
wazuhRun('linux345').then(data => {
console.log(data);
}).catch(err => {
console.log(err);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.