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

async/await调用Promise返回值始终为undefined的问题排查

问题根因

返回undefined是代码存在三个明确问题:

  • 语法错误:.then()回调中return value[0].deviceId )多了一个多余的右括号,代码解析阶段就会报错
  • 函数无返回值:connectedDevice是async函数,但内部只是执行了await加Promise链式调用,没有把最终结果return到函数外层,async函数无显式return时默认返回undefined
  • 错误被静默吞掉:.catch()仅打印错误日志,没有向外抛出错误或返回有效值,一旦接口请求失败,外层完全感知不到异常,只能拿到undefined

修复方法

优先用纯async/await写法,逻辑更直观,能避免链式调用的返回值断层问题,修正后代码:

const connectedDevice = async () => {
  try {
    const deviceList = await BleClient.getConnectedDevices(optionalServices);
    // 增加空值校验,避免无已连接设备时数组越界
    if (!deviceList || !deviceList.length) {
      throw new Error('无匹配的已连接设备');
    }
    return deviceList[0].deviceId;
  } catch (err) {
    console.error('获取已连接设备失败:', err);
    // 必须向外抛出错误,不要静默吞错,方便外层做异常处理
    throw err;
  }
}

如果要保留.then链式写法,只需要把整个Promise实例作为返回值返回即可,注意修正语法错误:

// 直接返回Promise,不需要额外加async包裹
const connectedDevice = () => {
  return BleClient.getConnectedDevices(optionalServices)
    .then(value => {
      if (!value || !value.length) {
        throw new Error('无匹配的已连接设备');
      }
      return value[0].deviceId;
    })
    .catch(err => {
      console.error('获取已连接设备失败:', err);
      throw err;
    });
}

修复后通过const conn = await connectedDevice();即可拿到正确的deviceId值,注意await关键字必须在async函数上下文中使用,否则会触发语法错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:57:20