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);
});

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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: stackoverflow.com/questions/35832955/…. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.