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
相关产品推荐
相关产品推荐

