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

为何JavaScript的async/await版异步请求无输出?对比回调与Promise版

为什么async/await版的HTTP请求没有输出?

核心原因是**https.get()本身不返回Promise**,你用await等待它,只会等到请求发起成功、拿到response对象就继续往下走,但响应数据的接收(data/end事件)是后续的异步过程。

Node.js脚本在同步代码和微任务都执行完后,会自动退出进程。你的async函数在拿到response后,就已经执行到函数末尾了,此时进程没有需要等待的pending Promise或其他异步任务,很可能在end事件触发、console.log(data)执行前,进程就已经结束了,所以看不到任何输出。

对比另外两个版本能正常工作的原因:

  • 回调版:https.get()的回调里注册了end事件监听器,Node.js会因为存在活跃的事件监听器而保持进程运行,直到end事件触发、回调执行完毕。
  • Promise版:把整个数据收集的过程包装成了Promise,resolve在end事件触发时才会调用,then里的代码会在数据准备好后执行,同时pending状态的Promise会让进程等待微任务完成,所以能正常输出。

修复后的async/await版本

把数据收集的异步逻辑封装成Promise,再用await等待这个Promise完成:

const https = require('https');

async function getDataFromServer() {
  try {
    // 把整个HTTP请求+数据收集过程封装成Promise
    const data = await new Promise((resolve, reject) => {
      https.get('https://jsonplaceholder.typicode.com/posts/1', (response) => {
        let rawData = '';
        response.on('data', (chunk) => {
          rawData += chunk;
        });
        response.on('end', () => {
          resolve(rawData);
        });
      }).on('error', (error) => {
        reject(error);
      });
    });
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getDataFromServer();

这样修改后,await会等待整个数据接收完成,进程也会因为pending的Promise保持运行,直到数据输出完毕。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:52:55