Hello all.
I’ve made a simple afterSave function with the Parse query inside.
Parse.Cloud.afterSave("Bookings", async (request) => {
console.log("*** Received a new afterSave function on Bookings table with request: ", request);
// Request bookings table posting ID
const postingID = request.object.get('postingID');
console.log("*** Got posting ID for booking: ", postingID);
const clientID = request.object.get('clientID');
console.log("*** Got client ID for booking: ", clientID);
// List of owners to make conversations and send messages
// Adding a client itself to create conversation and message
var recipientsList = [clientID];
// Query the posting
const CurrentPosting = Parse.Object.extend('Postings');
const postingQuery = new Parse.Query(CurrentPosting);
postingQuery.get(postingID, { useMasterKey: true }).then((currentPosting) => {
// The posting retrieved
const postingOwnerID = currentPosting.get('ownerID');
// Get the owner and check if he is a main owner
const ownerQuery = new Parse.Query(Parse.User);
ownerQuery.get(postingOwnerID, { useMasterKey: true }).then((currentOwner) => {
// Check if the owner is main owner
const mainOwner = currentOwner.get('mainOwner');
if (mainOwner == false) {
console.log('*** Current owner is not main owner');
// Add owner ID to ownersList
recipientsList.push(postingOwnerID);
//console.log('*** Recipients list for this order will be: ', recipientsList);
} else {
console.log('*** Current owner is main owner');
// Select country and city from main owner
const ownerCountry = currentOwner.get('country');
const ownerCity = currentOwner.get('city');
// Find all the owners in this city and country and add them to list
const ownersQuery = new Parse.Query('User');
ownersQuery.equalTo('isOwner', true);
ownersQuery.equalTo('isBlocked', false);
ownersQuery.equalTo('country', ownerCountry);
ownersQuery.equalTo('city', ownerCity);
ownersQuery.find( { useMasterKey: true })
.then(function(owners) {
owners.forEach((owner) => {
const ownerID = owner.id;
console.log('*** Owner ID found: ', ownerID);
recipientsList.push(ownerID);
//console.log('*** Recipients list for this order will be: ', recipientsList);
});
})
.catch(function(error){
console.log('*** Error getting owners for current country and city !!!', error);
});
}
}), (error) => {
console.log('*** Cannot get posting owner: ', error)
};
console.log('*** Recipients list for this order will be: ', recipientsList);
// Create main Conversation(s)
const MainConversation = Parse.Object('Conversations');
}, (error) => {
console.log('*** Error retreiving posting for booking !!!', error);
});
});
The problem is that the code is not waiting for the query and I have only initial value of recipientsList variable on the code execution.
I need to add async / await but I cannot understand where to put it in JavaScript/ Cloud Code.