gpt4 book ai didi

javascript - 在 Promise() 中使用 while 循环

转载 作者:行者123 更新时间:2023-11-30 20:12:43 26 4
gpt4 key购买 nike

我有一个用户列表,我正在检查所有用户的某些详细信息。我正在使用 sequelize js 和 express。我想知道我们可以像这样使用 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);
})
});

最佳答案

避免 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);
});
});

关于javascript - 在 Promise() 中使用 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52232632/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com