Search code examples
javascriptnode.jspromisebluebird

stop while loop inside a promise in node js


I am working on a problem in which i have to generate a unique id for user but i am not able to figure it out how to break the while loop inside a Promise.Following function will find if the user with same ref_id exist or not and then return me a resolve promise.

function makeRefId() {

return new Promise(function(resolve , reject){
    var refId = null;
    var flag = true;
    var tempUser ;

    do{
        refId = randomId(); //this will return a random string
        console.log(refId);

        tempUser =   User.findOneAsync({ref_id:refId}).then(function(user){
            if(user == null)
            {
                flag = false;
                resolve(refId);
            }
        });

    }while(flag);

});
}

Solution

  • I'd go with a recursive function for this. While loops don't mix well with promises, as they're asynchronous.

    function makeRefId() {
        const refId = randomId();
        return User.findOneAsync({ ref_id: refId }).then((user) => {
            if (!user) {
                return refId;
            } else {
                return makeRefId();
            }
        });
    }
    

    You'd then use it as so:

    makeRefId().then(refId => {
        // Do whatever with refId
    });