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

如何解决Promise的.text()方法返回Undefined的问题?

问题分析与解决

你的代码出现Test: undefined的原因有两个:

  1. test函数没有返回异步操作的Promise
    你的test函数里调用了fetch,但没有把fetch返回的Promise链返回出去,所以调用test()时,函数默认返回undefined,根本拿不到接口返回的文本。

  2. 同步回调里没有等待异步操作完成
    路由回调是同步执行的,直接调用test()不会等接口请求完成就执行了res.render,这时候自然拿不到结果。


修改后的完整代码

/* GET users listing. */
// 把路由回调改成async函数,支持await
router.get('/', async function(req, res, next) {
  // 等待test函数的异步操作完成,拿到返回值
  const message = await test();
  res.render('index', { title: ' Test: ' + message });
});

function test() {
  const url = 'http://backend:5000/api';
  // 返回fetch的Promise链,让调用方可以等待结果
  return fetch(url)
    .then(response => {
      console.log("This is working");
      return response.text();
    })
    .catch(error => {
      console.log("请求出错");
      return "Error";
    });
}

关键说明

  • 给test函数加上return,把fetch的Promise返回出去,这样外部才能通过await或者.then()获取异步结果。
  • 路由回调声明为async,用await等待test()的结果,确保拿到接口返回的文本后再渲染页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 09:12:53