Search code examples
parse-platformparse-cloud-code

Parse : Multiple queries with an array returning only when finished


trying CloudCode out for the first time and loving it.

I am writing an iOS app that passes phone numbers to CloudCode to see if a phone number already has the app.

The problem is its firing the success block before the queries finish. I am guessing I need to know how many queries there are and work out if on the last one? I also seen this .then function?

Parse.Cloud.define("processNumbers", function(request, response) {

    Parse.Cloud.useMasterKey();
    var phoneNumbers = request.params.phoneNumbers;

    phoneNumbers.forEach(function(entry) {

        var query = new Parse.Query(Parse.User);
        //query.equalTo("username", entry);

        query.find({
            success: function(results) {
                console.log("has app");

            },
            error: function() {
                console.log("not found");

             }
        }); 

        console.log(entry);

    });

    response.success(phoneNumbers);
});

Solution

  • You could do use promise to perform task in series or parallel.

    ref. Promises in Parallel, Promises in Series

    The following is a parallel version which use Parse.Promise.when. The promise when will be resolved when all of its input promises is resolved.

    Parse.Cloud.define("processNumbers", function(request, response) {
    
        Parse.Cloud.useMasterKey();
        var phoneNumbers = request.params.phoneNumbers;
        var promises = [];
    
        phoneNumbers.forEach(function(entry) {
    
            var query = new Parse.Query(Parse.User);
            //query.equalTo("username", entry);
    
            promise.push(
                query.find().then(function(results) {
                    console.log("has app");
    
                }, function() {
                    console.log("not found");
    
                });
            ) 
    
            console.log(entry);
    
        });
        return Parse.Promise
            .when(promises)
            .then(function() {
                response.success(phoneNumbers);
            });
    
        response.success(phoneNumbers);
    });
    

    p.s. not tested yet, use at your own risk