Q:

Use own promises in Parse cloud code

I would like to save a registrationId which is generated randomly in Parse cloud code, so I need to check if that value is already in the DB, I have to do this in a recursive way until I get the right string. Here is what I tried so far, the problem is that findRegistrationId() is not a promise so I cannot use then() is there any way to make it a promise or any other workaround? for cloudcode
function getRandomString()

{
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
    var string_length = 4;
    var randomstring = '';

    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum + 1);
    }
    return randomstring;
}
function findRegistrationId()
{
    console.log("Enter findRegistrationId")
    var randomString = getRandomString();
    var query = new Parse.Query("Book");

    query.equalTo("registrationId", randomString);

    query.find.then(function(results){
        if(results.length === 0)
        {
            console.log("no registrationId duplicated")
            return randomString;
        }
        //if there is other registrationId we concatenate
        else
        {
            console.log("registrationId duplicated let's recursive it")
            return findRegistrationId();
        }
    },function(error){
        return error;
    })

}

// Use Parse.Cloud.define to define as many cloud functions as you want.
// Gets the unique cool BC identificator. The real glue of BC!
Parse.Cloud.define("GetBookId", function(request, response) {

    var promise = findRegistrationId();

    promise.then(function(result){

        console.log("success promise!!")
        response.success(result);

    }, function(error){
        console.error("Promise Error: " + error.message);

        response.error(error);

    });

});

A:

You can write your function like this:
function findRegistrationId()
{
    console.log("Enter findRegistrationId")
    var randomString = getRandomString();
    var query = new Parse.Query("Book").equalTo("registrationId", randomString);

    var promise = new Parse.Promise();

    query.find().then(function(results) {
        if (results.length == 0)
        {
            promise.resolve(randomString);
        }
        else
        {
            findRegistrationId().then(function(result) {
                promise.resolve(result);
            }, function(error) {
                promise.reject(error);
            });
        }
    }, function(error) {
        promise.reject(error);
    });

    return promise;
}

A:

@arghbleargh posted a great solution, and I'm just posting a version that uses direct returning of promises rather than resolving/rejecting, which is an anti-pattern (see https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns eg): 
function findRegistrationId()
{
    console.log("Enter findRegistrationId")
    var randomString = getRandomString();
    var query = new Parse.Query("Book").equalTo("registrationId", randomString);    

    return query.find().then(function(results) {
        if (results.length == 0)
        {
            return randomString;
            // or, you could return Parse.Promise.as(randomString);
            // but the explicit promise isn't required
        }
        else
        {
            findRegistrationId().then(function(result) {
                return result;
                // or, you could return Parse.Promise.as(result);
                // but the explicit promise isn't required
            }, function(error) {
                return Parse.Promise.error(error);
            });
        }
    }, function(error) {
        return Parse.Promise.error(error);
    });    
}

