這將是一個簡單的答案,但我有這段代碼,它驗證資料庫中是否存在記錄,它確實存在,并且我從 API 呼叫中獲得了狀態 500,但不斷在我的表中創建重復記錄。
exports.createBet = async (req, res)=>{
betBody = req.body;
newBalance = 0.0;
Bet.findOne({
where: {
[Op.and]: [
{match_id: betBody.matchId},
{user_id: betBody.userId}
]
}
}).then(data=>{
if(data){
return res.status(500).send({message: "Bet already made for this match"});
}
})
.catch(err=>{
return res.status(500).send({ message: "Error creation the bet: " err.message});
});
balnce = await User.findOne({
where:{
id: betBody.userId
}
})
.then(data=>{
if(data.balance < betBody.betAmount){
return res.status(500).send({ message: "Not enough balance to make that bet."});
}
return data.balance;
})
.catch(err=>{
return res.status(500).send({ message : "Error getting the user in the bet creation: " err.message})
});
Bet.create({
match_id: betBody.matchId,
bet_amount: betBody.betAmount,
selected_winner: betBody.teamSelect,
user_id: betBody.userId
})
.then(data=>{
res.json(data)
})
.catch(err=>{
return res.status(500).send({ message: "Error creating the bet: " err.message})
});
newBalance = balnce - betBody.betAmount;
User.update(
{ balance: newBalance},
{ where: {id: betBody.userId}}
)
.catch(err=>{
res.status(500).send({ message: "Error getting user: " err.message})
});
};
這是api呼叫的回應
這是我表中的重復記錄
uj5u.com熱心網友回復:
您應該使用承諾鏈(或正確的異步/等待)來解決此問題,當請求到達 createBet 函式時,每個資料庫呼叫(沒有等待一個)都在并行執行,它會在檢查現有記錄的同時創建一條新記錄。
注意:有時您可能會收到回應已發送錯誤。res.send 不會停止執行,它會回傳回應,但剩余的代碼仍將執行。
exports.createBet = async (req, res) => {
betBody = req.body;
newBalance = 0.0;
try {
const bet = await Bet.findOne({
where: {
[Op.and]: [{ match_id: betBody.matchId }, { user_id: betBody.userId }],
},
}).catch((err) => {
throw { message: "Error creation the bet: " err.message };
});
if (bet) {
throw { message: "Bet already made for this match" };
}
//... handle the cases like above, must use await
} catch (err) {
res.status(500).json({ message: err.message });
}
};
uj5u.com熱心網友回復:
此問題會導致您的資料庫中保存的記錄沒有所有欄位都試圖截斷您的表并重新開始,
我認為在您的查詢中始終找到一條記錄(資料),這就是我們面臨此類錯誤的原因
如果它不起作用,請嘗試使用記錄來自findOne查詢的資料來除錯您的代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/414725.html
標籤:
上一篇:如何將資料從node.js傳遞到本地javascript,保持陣列功能?
下一篇:表達具有奇怪行為的方法
