jaredrada
jaredrada

Reputation: 1150

node q promise recursion

I have a async function that returns a random student. Now I want a function that returns two unique students- the source of my problems.

    getTwoRandom = function(req) {
        var deferred = Q.defer();

        Q.all([
            Student.getRandom(req), 
            Student.getRandom(req)
            ])
        .then(function(students){
            if(students[0]._id !== students[1]._id) { //check unique
                deferred.resolve(students);
            } else {
                //students are the same so try again... this breaks
                return getTwoRandom(req);
            }
        });

        return deferred.promise;
    };

then further down I have something like this:

getTwoRandom(req).then(function(students) {
     //do what I want...
});

The problem is when I do return getTwoRandom(req); the .then() function down the lines doesnt fire... is this returning a different promise that .then() isnt using?

Upvotes: 2

Views: 1232

Answers (1)

Jakob
Jakob

Reputation: 24360

You've over-complicated it quite a bit :)

You can do it like this instead:

getTwoRandom = function(req) {
    return Q.all([
        Student.getRandom(req), 
        Student.getRandom(req)
    ]).then(function(students) {
        if(students[0]._id !== students[1]._id) {
            return students;
        } else {
            return getTwoRandom(req);
        }
    });
};

Now, why does this work? The result of Q.all is always a new promise (no need to create a new deferred). Whatever value you return (ike students) will be wrapped in this new promise. If instead an actual promise is returned (like getTwoRandom(req)), then that promise will be returned. Which sounds like what you wanted to do.

Upvotes: 2

Related Questions