0

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);
});
Burf2000
  • 5,001
  • 14
  • 58
  • 117

1 Answers1

4

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

mido
  • 24,198
  • 15
  • 92
  • 117
eth3lbert
  • 813
  • 5
  • 5
  • is there anything else that you have to do when the inner promises (in the array) are themselves queries that return a result? I can get it to work when I return .as(something), but not when adding a nested promise: http://stackoverflow.com/questions/35832955/parse-cloud-code-sub-queries-with-parallel-promises. Thanks! – Chris Conover Mar 07 '16 at 04:57