You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

async函数调用net.connect提前返回undefined,如何获取正确结果?

问题根源

  • 你写在net.connect回调、error事件回调里的return语句,只会把值返回给回调函数本身,完全不会作用于外层的isReachable函数
  • net.connect是回调风格的异步API,你的async函数没有等待这个异步操作执行完成,也没有返回任何值,所以默认返回的Promise会直接resolve为undefined,这就是你先打印Promise { undefined }、后打印true的原因

修复方案

把网络连接逻辑手动封装到Promise中,在异步操作完成时通过resolve返回结果即可,同时记得用完销毁连接避免资源泄漏:

async function isReachable(hostname, port) {
  return new Promise((resolve) => {
    const connection = net.connect(port, hostname, () => {
      // 连接成功,销毁连接后返回true
      connection.destroy();
      resolve(true);
    })
    .on('error', () => {
      // 连接失败,销毁连接后返回false
      connection.destroy();
      resolve(false);
    });
  });
}

调用方法

因为返回的是Promise对象,你需要用await或者.then来获取最终结果:

// 方式1:await调用(必须放在其他async函数内)
const reachable = await isReachable('127.0.0.1', 80);
console.log(reachable); // 输出正确的布尔值

// 方式2:.then链式调用
isReachable('127.0.0.1', 80).then(reachable => {
  console.log(reachable);
});

内容的提问来源于stack exchange,提问作者minomy13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 23:27:05