我是 javascript 新手,我很难让我的响应返回以等待我的 mongodb 查询在 forEach 循环内完成运行。
我的代码是当前:
exports.applyThesaurus = (req, res, next) => {
let numModified = 0;
var prom = new Promise((resolve,reject) => {
req.file.forEach((obj,idx) => {
wos.updateMany(
{ creator: req.userData.userId},
{ $set: { [req.body.field+".$[element]"] : obj.replaceWith } },
{ arrayFilters: [ { "element": { $in: obj.replaced } } ] }
).then((result) => {
console.log(result.nModified)
numModified += result.nModified
})
.catch((err) => {
res.status(500).json('There was an error while applying the thesaurus.');
})
if( idx === req.file.length -1) {
resolve()
}
})
})
prom.then(() => {
console.log('im returning');
res.status(200).json({message: numModified + ' itens replaced successfully'});
})
}
发生的情况是“我正在返回”控制台日志在一个日志结果之前触发。nModified
我需要能够运行所有 updateMany 查询,然后以更新的项目数量进行响应。
有什么建议吗?非常感谢!
答案 0 :(得分:0)
您的代码试图在 updateMany
执行之前返回 resolve。
if (idx === req.file.length - 1) {
resolve() // this resolve get's executed befour updateMany get executed
}
这可能会让您更好地了解 callbacks 及其发生的原因。如前所述,如果您想在 updateMany
完成执行后解决承诺,您需要按如下方式更新您的代码:
exports.applyThesaurus = (req, res, next) => {
let numModified = 0;
var prom = new Promise((resolve, reject) => {
let updateManyPromisesArray = []
req.file.forEach((obj, idx) => {
updateManyPromisesArray.push(wos.updateMany({
creator: req.userData.userId
}, {
$set: {
[req.body.field + ".$[element]"]: obj.replaceWith
}
}, {
arrayFilters: [{
"element": {
$in: obj.replaced
}
}]
}))
Promise.all(updateManyPromisesArray)
.then((result) => {
if (idx === req.file.length - 1) {
resolve()
}
})
.catch((err) => {
res.status(500).json('There was an error while applying the thesaurus.');
})
})
})
prom.then(() => {
console.log('im returning');
res.status(200).json({
message: numModified + ' itens replaced successfully'
});
})
}
此外,您应该开始使用 async and await 来避免此类 callback hells 情况。