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

Node.js发起GET请求后如何在回调外部获取返回结果

问题原因

https.get 是Node.js内置的异步IO方法,调用后不会阻塞后续同步代码的执行,会直接向下运行,因此你代码中末尾的console.log会先执行,此时请求还未返回,data 还未被赋值,自然拿不到结果。另外你原有代码中data未初始化赋值为空字符串,拼接chunk时会把undefined转为字符串拼在结果开头,需要注意修正。

解决方案

方法1:回调函数封装

把需要用到请求结果的逻辑封装为回调函数,在请求完成的end事件中触发调用:

const https = require('https');

function fetchData(callback) {
  let data = '';
  https.get('https://www.example.com', (resp) => {
    resp.on('data', (chunk) => {
      data += chunk;
    });
    resp.on('end', () => {
      callback(null, data);
    });
  }).on("error", (err) => {
    callback(err);
  });
}

// 调用,所有用到返回数据的逻辑都放在回调里执行
fetchData((err, data) => {
  if (err) {
    console.log("Error: " + err.message);
    return;
  }
  console.log("拿到返回结果:", data);
  // 后续处理data的逻辑都写在这里
});

方法2:Promise封装

适合需要链式调用的场景,把异步逻辑包装成Promise实例:

const https = require('https');

function fetchData() {
  return new Promise((resolve, reject) => {
    let data = '';
    https.get('https://www.example.com', (resp) => {
      resp.on('data', (chunk) => {
        data += chunk;
      });
      resp.on('end', () => {
        resolve(data);
      });
    }).on("error", (err) => {
      reject(err);
    });
  });
}

// 调用
fetchData()
  .then(data => {
    console.log("拿到返回结果:", data);
    // 后续处理逻辑
  })
  .catch(err => {
    console.log("Error: " + err.message);
  });

方法3:结合async/await使用

写法最贴近同步逻辑,可读性最高,需要在Promise封装的基础上使用:

const https = require('https');

function fetchData() {
  return new Promise((resolve, reject) => {
    let data = '';
    https.get('https://www.example.com', (resp) => {
      resp.on('data', (chunk) => {
        data += chunk;
      });
      resp.on('end', () => {
        resolve(data);
      });
    }).on("error", (err) => {
      reject(err);
    });
  });
}

// 调用,必须放在async函数中
async function main() {
  try {
    const data = await fetchData();
    console.log("拿到返回结果:", data);
    // 后续可以直接在这里使用data,写法和同步逻辑一致
  } catch (err) {
    console.log("Error: " + err.message);
  }
}

main();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:45:04