Reputation: 1455
Scenario:
1. Generate Pincode.
2. Search database whether the pincode exists.
3. If exists, go back to step 1 and step 2.
4. If does not exist, proceed to do something else.
My code:
var pinCode = Math.floor(1000 + Math.random() * 9000);
db.transactionDetails.findOne({
where: {transaction_pincode:pinCode}
}).then(transactionDetail => {
if(transactionDetail == null){
db.transactionDetails.create({
customer_id:customerID,
transaction_amount:transactionAmount,
transaction_pincode:pinCode
})
The code above works fine if the pincode does not exist. But how can I run the same piece of code if pincode exists ?
Upvotes: 1
Views: 119
Reputation: 58573
You can do that like :
function checkPincode(){
var pinCode = Math.floor(1000 + Math.random() * 9000);
return db.transactionDetails.findOne({
where: {transaction_pincode:pinCode}
}).then(transactionDetail => {
if(transactionDetail == null){ // <------- Check if no such pincode
return db.transactionDetails.create({
customer_id:customerID,
transaction_amount:transactionAmount,
transaction_pincode:pinCode
})
} else {
return checkPincode(); // <------- Call it self if pincode exists
}
});
}
checkPincode().then(data => { // <------ Initiate checkPincode function
console.log(data);
});
Upvotes: 2