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

Async functions执行顺序异常,mongoose.find未完成就提前执行后续代码

问题原因
  • mongoose.connect 本身为异步方法,返回Promise实例,代码中未添加await关键字,程序不会等待数据库连接完成就会继续执行后续逻辑
  • mongoose.model('things').find() 使用了回调函数的调用方式,该方式不会返回可等待的Promise对象,asyncFunction 不会等待回调内的// do stuff with things逻辑执行完成,就会继续向下执行console.log('something')并结束函数运行,外层的await asyncFunction()自然无法感知到未完成的查询操作,会直接执行后续的// go do something else逻辑
修复方案

Mongoose 的所有异步API都同时支持回调调用和Promise调用,要配合async/await使用,直接省略回调参数即可拿到可等待的Promise实例,修复后代码如下:

const asyncFunction = async () => {
     // 等待数据库连接完成
     await mongoose.connect(`mongodb+srv://...`);
     mongoose.model('things', {data:String});
     // 省略回调参数,await获取查询结果
     const things = await mongoose.model('things').find();
     // 执行原回调内的逻辑
     // do stuff with things 
     console.log('something'); 
}

// 原代码定义函数时遗漏了等号,此处补上
const otherAsyncFunction = async () => {
     await asyncFunction();
     // go do something else 
}
otherAsyncFunction();

如果确实需要保留回调写法处理查询结果,可以手动将查询操作包装为Promise实例,即可被外层await识别:

const asyncFunction = async () => {
     await mongoose.connect(`mongodb+srv://...`);
     mongoose.model('things', {data:String});
     // 手动包装Promise
     await new Promise((resolve, reject) => {
       mongoose.model('things').find((err, things)=>{
          if (err) return reject(err);
          // do stuff with things 
          resolve();
       })
     })
     console.log('something'); 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:24:04