在NodeJS中使用do-while循环来检查Firebase数据库中是否存在

时间:2018-08-20 07:46:23

标签: node.js firebase promise do-while

当用户注册一个新帐户时,我想生成一个参考代码。我正在使用do-while循环来检查数据库中是否存在参考代码,但是尽管数据库中的记录很小,该循环仍至少运行2次。当我尝试运行代码时,它被卡住并永远等待响应。

这是我的工具:

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;
}

0 个答案:

没有答案