Parse: Fulfill multiple queries in the Parse Cloud code function. The second request does not work

I am trying to run multiple queries inside the Parse cloud function. The second request fails

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

});

+4
source share
1 answer

The problem is async requests. You do not wait for the request to complete before calling response.success().

Think about what you are calling in firstPhoneNumberQuery.find(), for example, putting eggs in a boil, blocks successand error- this is what you will do when it is done.

response.success() , , , , "".

promises, , response.success() success :

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

, then().

promises :

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

+4

All Articles