DEV Community

Discussion on: Sorting arrays in Javascript by date

Collapse
 
rhymes profile image
rhymes

I think the sorting is working, is just that the fetching of the date is asynchronous, which means that sometimes you get the dates BEFORE the sort is called, sometimes you get it after (If you click a few times you'll notice that the objects in array sometimes have the date, sometimes they don't).

Inside getBranchNames you call getCommitDate and inside it you call a HTTP GET to retrieve the date, but the JS doesn't guarantee that the callback is going to finish before the loop is done, which means you might call sort on an unfinished array.

It's not a super easy solution, because you're essentially sending an async call for each commit and hoping the GET finishes before the sort function is called.

Some possible solutions:

  1. you make those Ajax calls synchronous, but you're going to block the UI until they all return
  2. you switch to jQuery and wait for multiple requests to finish, an example here: stackoverflow.com/a/6558326/4186181
  3. you use ES6 and things like Promise.all + the fetch API or a third party library but I think it'd be too much to learn in one go just for this example
Collapse
 
thefern profile image
Fernando B 🚀 • Edited

Thanks for the awesome tips. I was looking into the promises. So essentially I need to perform getBranches, getCommitDate, and then sort specifically in that order. I was sort of thinking it was something wrong with my async calls since well I had zero experience before today.

Edit: Nvm not in that order, I need to loop to all branches first to get all the dates then sort.

Collapse
 
ahferroin7 profile image
Austin S. Hemmelgarn

Quick tip on the note of async stuff: If you can afford to not run on Internet Explorer and Opera Mini, use Promises. They solve most of the issues inherent in the older async functionality present in JavaScript, and also tend to be more efficient.

Thread Thread
 
thefern profile image
Fernando B 🚀

I think I can live without IE lol.