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

Node.js中如何解决Promise <pending>状态问题?

解决异步函数调用时Promise处于pending状态的问题

问题原因

你定义的newly是async函数,这类函数默认返回一个Promise对象。直接调用它时,Promise还未完成(处于pending状态),所以控制台会打印Promise { <pending> };同时res.send()无法正确处理Promise对象,导致Postman收不到有效返回内容。

解决方案

方案1:用async/await处理(推荐,代码更易读)

把Express路由的回调函数声明为async,然后用await等待异步函数的Promise完成,拿到实际返回值:

const myNewly = require('./pro');

app.post('/getBalance/type', jsonParser, async function(req, res) {
  try {
    // 等待异步函数执行完成,拿到结果
    const balanceResult = await myNewly.newly(account, req.body.address);
    console.log(balanceResult); // 输出实际账户数据
    res.send(balanceResult); // 将结果返回给客户端
  } catch (error) {
    // 捕获请求过程中可能出现的错误(比如API调用失败、JSON解析出错)
    console.error(error);
    res.status(500).send('获取余额失败');
  }
})

方案2:用Promise的.then()链式调用

如果不想修改路由回调为async,也可以通过Promise的.then()方法处理成功结果,.catch()处理错误:

const myNewly = require('./pro');

app.post('/getBalance/type', jsonParser, function(req, res) {
  myNewly.newly(account, req.body.address)
    .then(balanceResult => {
      console.log(balanceResult);
      res.send(balanceResult);
    })
    .catch(error => {
      console.error(error);
      res.status(500).send('获取余额失败');
    });
})

额外注意点

  • 确保account变量在路由回调中是已定义的有效值,否则可能导致API请求出错
  • 建议始终添加错误处理逻辑(try/catch或.catch()),避免未处理的Promise异常导致服务器崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:55:18