gpt4 book ai didi

node.js - 在nodeJS中生成数据库uniqueId

转载 作者:行者123 更新时间:2023-12-03 22:26:33 26 4
gpt4 key购买 nike

我需要为在 nodeJS 应用程序上注册的每个用户生成一个 uniqueID。

我使用 Sequelize 并创建了一个无限循环,直到生成 uniqueID。

如果我使用以下代码:

var breakLoop=false;
db.Contact.create({ first_name: req.body.first_name, last_name: req.body.last_name,
phone:req.body.phone, email:req.body.email, id_domain: req.body.id_domain }).
then( async function (item) {
while(!breakLoop) {
var coupon=Math.random().toString(36).slice(-5);
let found=await db.Coupon.findOne({ where: {coupon:coupon}});
if(!found) {
db.Coupon.create({ coupon: coupon, id_contact: item.id }).then(function (item) {
session.coupon=coupon;
return breakLoop=true;
}).catch(function (err) {
console.log(err);
return;
});
}
}
res.json({item:item.id});
});

我为每个用户生成2-3张优惠券;我知道我可以为此创建一个存储过程,但我想在 Node 中使用正确的用例;可能是我必须使用 Promise 但我不知道如何在无限循环中使用它。

最佳答案

使用带有 try 和 catch 块的 await 来更容易地理解流程。

var breakLoop = false;
db.Contact.create({
first_name: req.body.first_name, last_name: req.body.last_name,
phone: req.body.phone, email: req.body.email, id_domain: req.body.id_domain
}).
then(async function (item) {
while (!breakLoop) {
try{
var coupon = Math.random().toString(36).slice(-5);
let found = await db.Coupon.findOne({ where: { coupon: coupon } });
if (!found) {
try{
let newCoupon = await db.Coupon.create({ coupon: coupon, id_contact: item.id });
session.coupon = newCoupon;
breakLoop = true;
// you can also use break; to exit from the loop
}catch(error){
console.log("Error in creating new coupon " + error);
breakLoop = true;
// you can also use break; to exit from the loop
}
}
}catch(error){
console.log(error);
breakLoop = true;
// you can also use break; to exit from the loop
}
}
res.json({ item: item.id });
});

关于node.js - 在nodeJS中生成数据库uniqueId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57786665/

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