Node.js异步函数未等待Promise返回值问题求助
问题分析与修复
你的问题核心是没正确处理异步流程,导致函数提前返回空值,具体问题点:
createSupportDependencies函数没有返回任何值,所以await它的时候得到的是undefinedArray.map搭配异步函数时,会直接返回一堆Promise,但你没等待这些Promise全部完成,函数就已经执行结束了- 你在
map的回调里尝试返回doc,但这个返回值不会传递到外层的createSupportDependencies函数里,而且doc.save()是异步操作,你也没等待它完成就返回
以下是修复后的代码:
const createSupportDependencies = async (req, doc) => { // 用Promise.all等待所有support的异步操作完成 await Promise.all(req.body.supports.map(async (support) => { support.doc = doc.id if (support.role && support.role.slug) { const newRole = await Role.create(support.role) support.role = newRole.id } const newSupport = await Support.create(support) doc.supports.push(newSupport.id) })) // 所有support处理完后,统一保存doc并返回 return await doc.save() } export const createDoc = async (req, res) => { try { const doc = new Doc(req.body.doc) const docWithSupports = req.body.supports ? await createSupportDependencies(req, doc) : await doc.save() // 这里补上await,确保拿到保存后的文档而非Promise return res.status(200).json({ success: true, message: "Doc has been successfully created.", data: docWithSupports }) } catch (err) { return res.status(400).json({ success: false, message: err.message }) } }
修复说明:
- 用
Promise.all包裹map,确保所有support的创建和关联操作都完成后,再执行doc.save() createSupportDependencies现在会返回保存后的doc,await它就能拿到正确的结果- 补全
doc.save()前的await,确保拿到的是保存后的文档对象而非Promise
内容的提问来源于stack exchange,提问作者Nils Lopez
相关产品推荐
相关产品推荐

