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 ?
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);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.