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

JavaScript Async/Await:嵌套函数如何正确返回结果?

问题分析与修复

你的代码存在几个关键问题,导致始终返回undefined,逐个拆解说明:

1. findProductsByOrderId的核心错误

  • Mongoose的find方法如果传入回调函数,就不会返回Promise,因此你写的await完全无效。同时函数内部没有返回products变量,导致这个函数默认返回undefined。
  • 正确做法是去掉回调,直接用await接收查询结果并返回。

2. findCustomerOrder的多处错误

  • 拼写错误:custoemrId应为customerId,这个笔误会直接导致查不到订单。
  • 混合使用await和.then(),逻辑嵌套混乱,且.then()的回调函数没有返回值,导致await Order.find(...)最终得到undefined。
  • for(const r in result)是遍历对象键的写法,而result是数组,应该用for...of遍历数组元素;同时你打印的result._id是错误的,要访问每个元素的_id。
  • 整个函数没有返回值,调用它自然得到undefined。

修正后的代码

const findCustomerOrder = async (id) => {
    // 修正拼写错误:custoemrId -> customerId
    const orders = await Order.find({ customerId: id });
    if (orders.length === 0) {
        console.log("order not found");
        return;
    }
    // Order.find返回数组,这里遍历所有订单(如果只需要第一个可直接取orders[0])
    for (const order of orders) {
        const products = await findProductsByOrderId(order._id);
        if (products) {
            // 遍历产品数组打印每个产品ID
            for (const product of products) {
                console.log("Product ID: ", product._id);
            }
        }
    }
    // 如需返回结果,可组装数据后返回
    return { orders };
};

const findProductsByOrderId = async (id) => {
    try {
        // 去掉回调,直接await查询结果
        const products = await Products.find({ orderId: id });
        return products;
    } catch (err) {
        console.error(err);
        return 'error!!';
    }
};

额外提醒

  • 避免await和.then()混合使用,用await写线性逻辑更易读维护。
  • Mongoose的find方法返回数组,判断订单是否存在要检查orders.length,而非直接if(order)。
  • 错误处理尽量打印具体错误信息,方便排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:36:18