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

JS异步函数返回Promise而非预期值,请求排查代码问题

问题分析与修复方案

一、isDeviceAnExtendedNode函数的核心问题

  • 函数标记了async但没有任何有效返回值,内部then回调的操作和函数返回值完全无关,调用后只会得到一个值为undefined的Promise。
  • 用forEach遍历roles时,回调里的return false只是跳出当前迭代,既不会成为函数返回值,也无法终止遍历,根本达不到判断目标role是否存在的目的。
  • 未处理response或response[0]为空的边界情况,容易触发报错。

二、调用处getFilteredDevices的问题

  • 调用异步函数isDeviceAnExtendedNode时未处理异步逻辑,代码会直接跳过等待异步结果,执行后续的push操作,导致过滤逻辑完全失效。
  • 错误使用map函数:map的作用是生成新数组,此处仅需遍历设备列表,应改用适合异步场景的for...of循环。

修正后的isDeviceAnExtendedNode函数

const isDeviceAnExtendedNode = async (deviceId) => {
  const response = await getDevicesInfo(deviceId);
  // 处理边界情况:空响应、无设备数据、无roles字段
  if (!response || !response[0] || !response[0].roles) {
    return false;
  }
  // 用some判断是否存在目标role,找到后立即终止遍历
  // 逻辑说明:存在匹配role则返回false,否则返回true(可根据实际需求调整)
  return !response[0].roles.some(role => roleType.has(role));
};

修正后的getFilteredDevices函数

因涉及异步操作,函数需改为async,调用时要配合await:

export const getFilteredDevices = async (deviceList, deviceId, CedgeDeviceList) => {
  const filteredDevices = [];
  // 用for...of配合await,确保异步判断完成后再执行筛选
  for (const device of deviceList) {
    const isExtended = await isDeviceAnExtendedNode(device.instanceUuid);
    // 根据判断结果筛选设备(逻辑可根据实际需求调整)
    if (!isExtended) {
      filteredDevices.push({ text: device.hostname, value: device.instanceUuid });
    }
  }
  return filteredDevices;
};

关键补充说明

异步函数必然返回Promise,无法直接返回具体值,必须通过await或.then()获取最终结果,因此调用getFilteredDevices的地方也需要用await接收结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:10:31