嵌套Async/Await循环疑问:为何toArray()返回Pending Promise?
问题原因及解决方案
你的问题和for-of循环的执行顺序无关,核心是对MongoDB驱动API的理解有误:
db.collection('calendar').find()返回的是MongoDB游标对象,不是Promise。你用await等待这个游标完全没用,它不会触发实际的数据库查询,也不会等待任何异步操作完成。- 真正触发异步查询并返回数据的是游标上的
toArray()方法,这个方法才会返回Promise,你必须await它才能拿到最终的数组结果。
修正后的代码
for (const phase of user.phases) { for (const schedule of phase.schedules) { // 直接await toArray()的结果,它才是异步操作的Promise const populatedSchedule = await db.collection('calendar') .find({_id: schedule.calendar_id}) .toArray(); console.log('populatedSchedule'); console.log(populatedSchedule); // 现在能拿到实际数据了 } }
补充说明
for-of循环的顺序执行逻辑是没问题的——它确实会等待每一次循环里的await完成后再进入下一次循环。你之前的误解是把游标当成了异步结果,但游标只是查询的"句柄",真正的异步查询是在调用toArray()时才发起的,所以必须对toArray()的返回值用await。
内容的提问来源于stack exchange,提问作者HelloWorld
相关产品推荐
相关产品推荐

