You need to enable JavaScript to run this app. NodeJS http请求监听器如何等待第三方请求响应完成后再返回
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS http请求监听器如何等待第三方请求响应完成后再返回

核心前提说明

Node.js 采用单线程事件循环模型,不能直接同步阻塞主线程,否则异步回调(包括你监听的 remoteRes 事件)永远无法触发,会直接导致死锁。我们可以实现异步版本的 ManualResetEvent,语义完全对齐 C# 的实现,对原有代码结构的改动非常小。


ManualResetEvent TS 实现

class ManualResetEvent {
  private _resolve: (() => void) | null = null;
  private _isSet: boolean = false;

  constructor(initialState: boolean = false) {
    this._isSet = initialState;
  }

  // 对应C# Set() 方法,释放所有等待的执行流程
  set(): void {
    if (!this._isSet) {
      this._isSet = true;
      if (this._resolve) {
        this._resolve();
        this._resolve = null;
      }
    }
  }

  // 对应C# Reset() 方法,重置状态,后续waitOne会进入等待
  reset(): void {
    this._isSet = false;
  }

  // 对应C# WaitOne() 方法,异步等待直到set被调用
  waitOne(): Promise<void> {
    if (this._isSet) {
      return Promise.resolve();
    }
    return new Promise(resolve => {
      this._resolve = resolve;
    });
  }
}

适配到你的业务代码

仅需给原函数增加async关键字,其余业务逻辑完全保留:

// 仅新增async关键字,函数结构完全不变
async function onRequest(req: http.IncomingMessage, res: http.ServerResponse)
{
  // .... 原有逻辑不变
  const mre = new ManualResetEvent(false); // 初始化事件为未触发状态

  if(arguments are valid)
  {
    // ... prepare options for request 原有逻辑不变
    try
    {
        const remoteReq = https.request(options, (remoteRes) =>
        {
          remoteRes.on('data', (d) =>
          {
            // ... pass it to the response 原有逻辑不变
            res.write(d);
          });

          remoteRes.on('end', (d) =>
          {
            // POS 2: 触发事件,允许后续流程继续执行
            mre.set();
          });

          // 新增错误处理,避免请求出错时一直挂起
          remoteRes.on('error', () => {
            // 自定义错误处理逻辑
            mre.set();
          })
        });

        // 新增请求本身的错误处理
        remoteReq.on('error', () => {
          // 自定义错误处理逻辑
          mre.set();
        })

        remoteReq.end();
        // POS 1: 无需额外操作,mre初始化时已经是Reset状态
      }
    }
    catch
    {
      // 捕获同步错误后也要触发事件,避免无限等待
      mre.set();
    }
  }
  else
  {
    // 不需要走代理的场景直接触发事件
    mre.set();
  }

  // POS 3: 等待事件触发,仅新增await关键字即可
  await mre.waitOne();
  res.end("");
}

注意事项

  • 所有原有业务逻辑无需改动,仅新增了事件相关的几行代码,符合你不希望调整现有代码结构的要求
  • await 不会阻塞主线程,事件循环可以正常处理其他请求和回调,不会影响服务性能
  • 请务必补充所有错误分支的mre.set()调用,避免请求异常时一直挂起

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:00:01