ExpressJS与Mongoose查询异步问题:listElevators返回为空但控制台输出正常的求助
问题分析与解决方案:Express路由返回空数组但控制台输出有值
Hey Akram, let's break down why your listElevators array is empty in the API response but shows populated values in your console logs—this is a common asynchronous timing issue!
核心问题原因
Your code has two key async handling mistakes that cause this behavior:
- Mixed async patterns: You're combining
async/awaitwith.then()callbacks, which makes it hard to track when all asynchronous operations actually finish. forEachdoesn't wait for async callbacks: When you pass anasyncfunction toArray.forEach(), the loop doesn't pause to wait for each async operation to complete. This means yourres.status(200).json(listElevators)runs immediately, before any of theElevator.findById()calls have had a chance to push elements to the array. Theconsole.logworks later because it fires after those async operations finally finish, but by then the response has already been sent to the client.
修复后的代码
Here's a refactored version of your route that fixes these issues with consistent async/await and proper async loop handling:
router.get("/", async (req, res) => { try { const listElevators = []; // Fetch the target building document const building = await Building.findById(req.body.id); // Use for...of instead of forEach to properly wait for each async operation for (const equipId of building.Equipement) { const elevator = await Elevator.findById(equipId); // Check if any elevator equipment matches the target year (using Array.some for brevity) const hasMatchingYear = elevator.Equipement_elevator.some(equip => equip.Year === req.body.year); if (hasMatchingYear) { listElevators.push(equipId); } } // All async operations are complete—send the populated array res.status(200).json(listElevators); } catch (error) { // Add error handling to catch database or runtime issues res.status(500).json({ error: error.message }); } });
关键修改说明
try/catchblock: Added error handling to catch database lookup failures or other runtime errors (critical for robust Express routes).- Consistent
async/await: Removed.then()callbacks to make the async flow linear and easier to follow. for...ofloop: ReplacedforEachto ensure the loop waits for eachElevator.findById()call to finish before moving to the next iteration.Array.some(): Simplified the year-checking logic to avoid manual loop tracking—this is more concise and readable.
内容的提问来源于stack exchange,提问作者Akram T
相关产品推荐
相关产品推荐

