4

I am trying to run multiple queries inside Parse cloud function. Second query doesnt get executed

Parse.Cloud.beforeSave("PhoneNumbers", function(request, response) {

// Check if the same phone number for the same user exists
var PhoneNumbersObject = Parse.Object.extend('PhoneNumbers');

var duplicationQuery = new Parse.Query(PhoneNumbersObject);
duplicationQuery.equalTo('user', Parse.User.current());
duplicationQuery.equalTo('phoneNumber', request.object.get("phoneNumber"));

duplicationQuery.count({
    success: function(count) {
        if (count > 0) {
            response.error("This number is already stored");
        }
    },
    error: function(error) {
        response.error("Error " + error.code + " : " + error.message + " when storing phone number");
    }
});

var firstPhoneNumberQuery = new Parse.Query(PhoneNumbersObject);
firstPhoneNumberQuery.equalTo('user', Parse.User.current());

firstPhoneNumberQuery.find({                           //  <<<<< find doesn't work
    success: function(results) {
        if ( results.length == 0 ) {
            console.log("User's first telephone number");     // <<< Never reaches here
            request.object.set("primary", true);
        } else {
            console.log("Hello");                      // <<< Never reaches here
        }
    },
    error: function(error) {
        console.log("Bye");
        response.error("Query failed. Error = " + error.message);
    }
});

response.success();

});

1 Answer 1

4

The issue is that queries are async. You're not waiting for the query to finish before calling response.success().

Think of your call to firstPhoneNumberQuery.find() like putting eggs on to boil, the success and error blocks are what you'll do when it is done.

The call to response.success() is like telling the cleaners you are done and they can toss whatever is still "cooking".

Use promises to avoid this issue, as well as moving the response.success() call inside your query's success handler:

duplicationQuery.count({
    // ... success / error as above
}).then(function() {
    var firstPhoneNumberQuery = new Parse.Query(PhoneNumbersObject);
    firstPhoneNumberQuery.equalTo('user', Parse.User.current());
    // return the promise so we can keep chaining
    return firstPhoneNumberQuery.find();
}).then(function(results) {
    // ... success for find
    // then call success() here
    response.success();
}, function(error) {
    // ... error block for find
});

As you can see, you can combine as many then() blocks as you need.

Learn more about promises and chaining here:

https://parse.com/docs/js_guide#promises

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

Comments

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.