我的两个变量“ soundTypeFound [0] .name”和“ req.soundTypes [iteration]”每次都必须相同,但五倍于其为假。
我认为循环比函数“ allSoundTypeQuery.GetSoundTypeByName(item,(soundTypeFound,err)=> {}”)更快,并且变量“ iteration”没有与循环相同的时间递增
谢谢您的帮助
async function checkSoundTypes (req, res, soundTypesString, error, next) {
let stop = false;
req.soundTypes = soundTypesString.split(',');
let iteration = 0;
for (let item of req.soundTypes) {
await allSoundTypeQuery.GetSoundTypeByName(item, (soundTypeFound, err) => {
if (err) {
return res.status(500).json({"error": "Cannot find the sound type in the DB"});
}
if (soundTypeFound.length <= 0 || soundTypeFound[0].name !== req.soundTypes[iteration]) {
stop = true;
}
iteration++;
if (iteration === req.soundTypes.length) {
if (stop === true) {
error.push("soundTypes");
return res.status(400).json(error);
}else if (err) {
return res.status(400).json(error);
}else {
next();
}
}
});
}
}
答案 0 :(得分:0)
由于您正在发送回调函数,它将不会等待并继续进行下一次迭代,因此会导致错误,现在该方法将返回promise,因为我们正在使用util模块的promisify方法,而不是等待解决的诺言,然后转到下一行。
const {promisify} = require('util');
async function checkSoundTypes (req, res, soundTypesString, error, next) {
let stop = false;
req.soundTypes = soundTypesString.split(',');
let iteration = 0;
for (let item of req.soundTypes) {
const getSoundTypeByName = promisify(allSoundTypeQuery.GetSoundTypeByName);
const soundTypeFound= await getSoundTypeByName(item);
if (!soundTypeFound) { // this you should check as per your response
return res.status(500).json({"error": "Cannot find the sound type in the DB"});
}
if (soundTypeFound.length <= 0 || soundTypeFound[0].name !== req.soundTypes[iteration]) {
stop = true;
}
iteration++;
if (iteration === req.soundTypes.length) {
if (stop === true) {
error.push("soundTypes");
return res.status(400).json(error);
}else if (err) {
return res.status(400).json(error);
}else {
next();
}
}
}
}