简体   繁体   English

得到'承诺{<pending> }' 使用 async-await 执行 tcp 客户端时的消息</pending>

[英]Getting 'Promise { <pending> }' message when using async-await to perform tcp client

I am performing tcp client using telnet-client node module.我正在使用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);

On running above code, I am getting Promise { <pending> }在运行上述代码时,我得到Promise { <pending> }

Please suggest what might be missing in my code请建议我的代码中可能缺少的内容

Since you're using it outside of a async function you need to treat it as a Promise:由于您在异步 function 之外使用它,因此您需要将其视为 Promise:

wazuhRun('linux345').then((result) => console.log(result));

async functions are a syntatic sugar around Promises, they get translated into Promises which is why you get Promise pending.异步函数是 Promises 周围的语法糖,它们被翻译成 Promises,这就是为什么你会得到 Promise 挂起。

If you were calling it from inside another async function you could use:如果您从另一个异步 function 内部调用它,您可以使用:

const code = await wazuhRun('linux345');

EDIT: About the null return, it could be that your function throws an error before your try/catch.编辑:关于 null 返回,可能是您的 function 在您的 try/catch 之前引发错误。

 wazuhRun('linux345')
    .then((result) => console.log(result))
    .catch((error) => console.log(error));

By adding a catch handler to your Promise you'll be able to see all errors thrown from within your async function.通过向 Promise 添加一个 catch 处理程序,您将能够看到从异步 function 中抛出的所有错误。

Use wazuhRun('linux345').then() the it will work fine.使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM