1

I'm trying to implement a sorting function for the records returned by a callback. The normal javascript a.value - b.value inline implementation is working. This is the working code that I have:

/aura/myComponent/myComponentHelper

$A.getCallback(function(result) {
  var cases = result.values.cases;
  cases.sort(function (a, b) {
    return b.CaseNumber - a.CaseNumber
  })
})

I wanted to make a separate function out of this inline function, so I did a function like this:

/aura/myComponent/myComponentHelper

getCases : function (component) {

  var self = this;

  ... other codes...

  myPromise.then (
    $A.getCallback(function(result) {
      var cases = result.values.cases;
      cases.sort(self.sortByCaseNumber());
      ... other codes ...
    })
  )
  .catch (
    ... other codes ...
  )
},

sortByCaseNumber : function(a, b) {
  return b.CaseNumber - a.CaseNumber
}

However, I'm encountering an Error in $A.getCallback() [Cannot read property 'CaseNumber' of undefined].

Inside the sortByCaseNumber function, the values of a and b are both undefined. Not sure why this is happening. I'm checking the values of the cases list right before I sort it and the list definitely contains an array of case objects, and the CaseNumber field is there.

1
  • Don't you need to pass the arguments a & b in the sortByCaseNumber(a,b) function?
    – Jayant Das
    Commented May 10, 2018 at 23:56

1 Answer 1

3

You're not supposed to call the function, but pass it in as a parameter to sort:

  cases.sort(self.sortByCaseNumber);

Note the lack of parentheses, because we're not actually calling the function, but instead passing it in as a parameter, much like you would a string or number (functions are formally of type Function, so you can use them like normal parameters). This is a pretty common idiom in JavaScript (setTimeout, setInterval, sort, map, reduce, Promise, etc) and also useful in Lightning (e.g. $A.getCallback), so you'll want to remember this.

1
  • you're right. Gotta go back and brush up on my javascript basics. Thank you.
    – SamuelDev
    Commented May 11, 2018 at 0:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .