我有一个用户列表,我正在检查所有用户的某些详细信息。我正在使用带有express的sequelize js。我想知道我们可以使用while循环来在数据库中搜索和保存数据。请帮助我。提前谢谢。
let royalty_bonus = async (sponsor) => {
return await new Promise((resolve, reject) => {
models.RoyaltyUser.findById(sponsor)
.then(async (sponsorRow) => {
let user_level = 1;
let sponsor_id = sponsorRow;
try {
while (sponsor_id != null && user_level <= 3) {
let level_length = await getLevel(sponsor_id.id, user_level);
if (user_level === 1 && level_length.length === 3) {
console.log('Level One Achieved By ', sponsor_id.id);
} else if (user_level === 2 && level_length.length === 9) {
console.log('Level Two Is Achieved By ', sponsor_id.id);
} else {
console.log('No Level');
}
await models.RoyaltyUser.findOne({where: {id: sponsor_id.sId}})
.then((sponsor_new_row) => {
sponsor_id = sponsor_new_row;
})
.catch((e) => {
console.log(' Inner Catch Error ', e.message);
reject();
});
user_level++;
}
resolve();
}
catch (e) {
reject(e);
}
})
.catch((e) => {
reject('catch ', e.message);
});
});
};
router.get('/royalty_user', async (req, res, next) => {
royalty_bonus(4)
.then(() => {
console.log('done');
})
.catch((e) => {
console.log('Catch two', e.message);
})
});
答案 0 :(得分:1)
避免使用Promise
constructor antipattern,避免使用return await
,并且不要将.then
回调与async
/ await
语法混合使用。您可以简化很多:
async function royalty_bonus(sponsor) {
const sponsorRow = await models.RoyaltyUser.findById(sponsor);
let user_level = 1;
let sponsor_id = sponsorRow;
while (sponsor_id != null && user_level <= 3) {
let level_length = await getLevel(sponsor_id.id, user_level);
if (user_level === 1 && level_length.length === 3) {
console.log('Level One Achieved By ', sponsor_id.id);
} else if (user_level === 2 && level_length.length === 9) {
console.log('Level Two Is Achieved By ', sponsor_id.id);
} else {
console.log('No Level');
}
const sponsor_new_row = await models.RoyaltyUser.findOne({where: {id: sponsor_id.sId}});
sponsor_id = sponsor_new_row;
user_level++;
}
}
router.get('/royalty_user', (req, res, next) => {
royalty_bonus(4).then(() => {
console.log('done');
}, e => {
console.log('Catch two', e.message);
});
});