0

When a user registers a new account, I want to generate a reference code. I'm using the do-while loop for checking exists of the reference code in the database but the loop keeps running at least 2 times although the records in the database are small. When I tried to run the code, it was stuck and keep waiting for the response forever.

Here's my implement:

function makeCode() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz0123456789"; 
    for (var i = 0; i < 8; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    console.log("### makeReferenceCode DONE ###")
    return text;
}

function genReferenceCode() {
    let referencePromise = new Promise((resolve, reject) => {
        let referenceRef = db.ref("ref_codes")
        var isExisted = true
        var code = makeCode().toUpperCase()
        console.log("### Generate Reference Code: " + code)
        do {
            referenceRef.orderByChild("code").equalTo(code).limitToFirst(1).on("value", function (snapshots) {
                if(snapshots.numChildren() > 0) {
                    console.log("### code existed ###")
                    code = makeCode().toUpperCase()
                    isExisted = true 
                } else {
                    console.log("### code not existed: " + code)
                    isExisted = false 
                    resolve({success: true, data: code})
                }
            }, function (error) {
                isExisted = true
                reject({success: false, error_code: "GEN_REF_CODE_00", error_msg: "Can't generate reference code!"})
            })
        } while (isExisted === true)
    })
    return referencePromise;
}
HoangNA
  • 163
  • 1
  • 12
  • That will block forever. Use Promises instead and call `.then` (or `await` or something) on them. – CertainPerformance Aug 20 '18 at 07:49
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Aug 20 '18 at 07:50
  • Why would you use a do-while loop? That sounds incredibly inefficient. Why not just fetch data where equal to the key, and if the result you get back is empty, then you know its not in use. – Ruan Aug 20 '18 at 11:50

0 Answers0