1

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 ?

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.