Hi Fletcher
The problem you are running into has to do with the synchronous execution of the App JS despite some functions actually being asynchronous, in this case .sort()
combined with referencing a related object. The related object reference inside of the sort function is executing asynchronously (ie object.relationship_name()
is technically an async function) but sort is not waiting for it to complete before evaluating your sort logic.
To solve this you need to first fetch and cache all relevant related objects so that you can access their values inside the sort function without having to call them with an asynchronous function.
Something like this. Let’s assume we want to sort our purchase orders by the name of the related customer.
function sortArray() {
view.sorted_array = DB.purchase_request.all().toArray();
var customers = DB.customer.all().toArray();
var customerLookup = {}
customers.forEach(function (c) {
customerLookup[c.id] = c;
})
view.sorted_array = view.sorted_array.sort(function (a, b) {
if (customerLookup[a.customer_id].name > customerLookup[b.customer_id].name) {
return 1;
} else if (customerLookup[a.customer_id].name < customerLookup[b.customer_id].name) {
return -1;
} else {
return 0;
}
})
}