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

NodeJS如何从Promise类型的外部方法获取值并在indexController中使用

问题根源

你当前的version函数没有设置返回值,所以调用它拿到的Promise默认携带的值为undefined,无法将数据库健康检查的结果传递到外层使用;同时你混合使用了await和.then()语法,没必要做冗余的嵌套处理。

修正方案

  1. 调整indexController里的version函数逻辑,直接用await拿到healthCheck的返回结果后按需返回即可,同时增加异常捕获处理被reject的错误场景:
// indexController
async function version() {
  try {
    const healthValue = await DB.healthCheck()
    console.log(healthValue)
    // 对外返回正常状态值
    return healthValue
  } catch (error) {
    console.log(error)
    // 对外返回异常状态值,可根据业务需要调整返回内容
    return error
  }
}
  1. 外层调用version函数拿结果时,因为它是异步函数,需要用await或者.then()接收返回值:
// 调用示例
async function getDbStatus() {
  const status = await version()
  // 此处即可拿到1(连接正常)或0(连接失败)的状态值使用
  console.log('数据库连接状态:', status)
}

额外优化提示

你定义的healthCheck已经手动返回了自定义Promise,不需要再加async关键字修饰,删除后不影响功能,还能减少冗余声明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:15:04