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

JavaScript多数组Promise解析异常:产品填充逻辑故障求助

问题分析与修复方案

代码里的核心问题

  • 变量名错误:await Promise.all(citiesPromises)中的citiesPromises从未定义,实际应该用你声明的promises变量。
  • 异步遍历逻辑错误:你在map的async回调里await查询结果后再push到数组,但async函数返回的是Promise,此时push的是未完成的异步操作返回的undefined,正确做法是把Product.find返回的Promise直接存入数组。
  • 未处理查询结果:products数组全程为空,没有把Promise.all的结果合并进去。
  • 查询效率低:多次发起数据库查询会导致性能问题,还会出现重复产品(同一个产品可能属于多个城市/类别)。

修复后的代码(保留原查询逻辑,修正错误)

import { Product } from "../../models";
import { Response } from "../../utils";

export default async function ProductsFilters(req, res) {
  try {
    const { Cities, Categories, Sort } = req.body;

    let products = [];
    const promises = [];

    if (Cities.length > 0) {
      // 直接把每个查询的Promise存入数组,而非等待结果
      Cities.forEach(city => {
        promises.push(Product.find({ City: city }));
      });
    }

    if (Categories.length > 0) {
      Categories.forEach(category => {
        promises.push(Product.find({ Category: category }));
      });
    }

    // 等待所有查询完成,获取结果
    const results = await Promise.all(promises);
    // 扁平化结果数组,并根据_id去重(避免重复产品)
    products = [...new Map(results.flat().map(item => [item._id, item])).values()];

    // 处理排序逻辑(根据你的Sort参数格式调整)
    if (Sort) {
      products.sort((a, b) => {
        if (Sort === 'price-asc') return a.Price - b.Price;
        if (Sort === 'price-desc') return b.Price - a.Price;
        // 其他排序规则自行补充
        return 0;
      });
    }

    // 根据产品数量返回对应响应
    if (products.length > 0) {
      Response(res, 200, true, "Të gjitha produktet u morën me sukses.", products);
    } else {
      Response(res, 404, false, "Asnjë produkt nuk u gjet në platformë.", null);
    }
  } catch (error) {
    console.error(error); // 打印错误便于调试
    Response(res, 500, false, "Gabim i brendshëm i serverit gjatë gjetjes së produkteve.", null);
  }
}

推荐优化方案(减少数据库请求,避免重复)

用MongoDB的$in和$or操作符一次性构建查询条件,只发起一次数据库请求,效率更高且不会出现重复数据:

import { Product } from "../../models";
import { Response } from "../../utils";

export default async function ProductsFilters(req, res) {
  try {
    const { Cities, Categories, Sort } = req.body;
    const query = {};
    const conditions = [];

    // 构建查询条件
    if (Cities.length > 0) {
      conditions.push({ City: { $in: Cities } });
    }
    if (Categories.length > 0) {
      conditions.push({ Category: { $in: Categories } });
    }

    // 合并查询条件
    if (conditions.length > 1) {
      query.$or = conditions;
    } else if (conditions.length === 1) {
      Object.assign(query, conditions[0]);
    }

    // 执行查询并处理排序
    let products = await Product.find(query);
    if (Sort) {
      products.sort((a, b) => {
        if (Sort === 'price-asc') return a.Price - b.Price;
        if (Sort === 'price-desc') return b.Price - a.Price;
        // 补充其他排序规则
        return 0;
      });
    }

    // 返回响应
    if (products.length > 0) {
      Response(res, 200, true, "Të gjitha produktet u morën me sukses.", products);
    } else {
      Response(res, 404, false, "Asnjë produkt nuk u gjet në platformë.", null);
    }
  } catch (error) {
    console.error(error);
    Response(res, 500, false, "Gabim i brendshëm i serverit gjatë gjetjes së produkteve.", null);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:01:39