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

封装Node.js https.get为Promise后返回Promise { <pending> } 如何解决?

问题解答

核心问题原因

  • 所有async关键字声明的函数,返回值本身就是Promise类型。你没有通过await或者.then()等待异步执行完成,就直接访问函数返回结果,自然会得到Promise { <pending> },和你封装的请求逻辑无关。
  • 原始myRequest存在隐藏bug:你收集的data是Buffer片段数组,不能直接传入JSON.parse解析,需要先拼接为完整Buffer再转为字符串才能正常解析JSON。

优化后完整实现

1. 封装请求工具函数

const https = require('https');

const myRequest = (url) => {
  return new Promise((resolve, reject) => {
    https.get(url, res => {
      // 兼容非2xx状态码的异常场景
      if (res.statusCode < 200 || res.statusCode >= 300) {
        return reject(new Error(`请求失败,状态码:${res.statusCode}`));
      }
      const chunks = [];
      res.on('data', chunk => chunks.push(chunk));
      res.on('end', () => {
        try {
          // 拼接Buffer并转字符串后再解析JSON
          const result = JSON.parse(Buffer.concat(chunks).toString());
          resolve(result);
        } catch (parseErr) {
          // 捕获JSON解析异常
          reject(parseErr);
        }
      });
    }).on('error', reject);
  });
};

2. 业务逻辑与正确调用方式

你写的getApi本身逻辑没问题,问题出在调用环节,必须等待异步执行完成才能拿到返回值:

async function getApi() {
  const url = '你的实际API地址';
  const data = await myRequest(url);
  const {high, open} = data.data[0];
  return `High: ${high} \n Open: ${open}`;
}

// 调用方式1:立即执行异步函数用await接收结果
(async () => {
  try {
    const result = await getApi();
    console.log(result);
    // 所有需要用到返回结果的逻辑都要写在这里
  } catch (err) {
    console.error('请求出错:', err);
  }
})();

// 调用方式2:通过then链式调用接收结果
getApi().then(result => {
  console.log(result);
}).catch(err => {
  console.error('请求出错:', err);
});

补充说明

你之前看到控制台先打印Promise { <pending> }后打印实际数据,就是因为你直接执行了console.log(getApi()),这行代码同步执行时异步请求还没完成,所以先输出pending,等异步逻辑跑完后getApi内部的打印才会输出实际接口返回内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:36:07