1

I am trying to sort an array of GitHub commit dates that I am pulling from the GitHub API with an $.ajax request. I have successfully gotten the data I want, which is returned from my function in the form of a promise.

However when I try to use .then to access the value of the promise, any array methods I use (like sort) have no effect. See code below:

// This works fine
async function getAllCommitDates() {
  const commitDates = [];
  const userRepos = await getRepoNames();
  const repoNames = userRepos.map((repo) => repo.name);

  repoNames.forEach(async (repo) => {
    const commits = await getRepoCommits(repo);
    commitDates.push(...getDates(commits));
  });

  return commitDates;
}

// Here is the problem
getAllCommitDates().then(function (res) {
  // Returns the expected array of date strings in "YYYY-MM-DD" format
  console.log(res);
  // Returns array in the exact same order, no sorting
  console.log(res.sort());
});

When I take a sample array of dates ie. ["2020-06-17", "2020-06-25", "2019-03-26", "2020-06-15"], and use .sort() it works fine. So I assume it has something to do with promises and the .then(), but what that problem is is beyond me.

Appreciate any help!

(EDIT) Adding image with log. The array from line 42 & 43 have the same contents, in the same order. enter image description here

Derek W.
  • 11
  • 2
  • Can you post an image of what does `console.log(res);` returns inside `.then()`. – palaѕн Jul 02 '20 at 04:57
  • If the data is coming through, could the problem be that you are trying to sort an array of strings, not dates? -> https://stackoverflow.com/questions/30691066/sort-a-string-date-array – MattJHoughton Jul 02 '20 at 05:06
  • The reason you see the right results in your console is because of this ~ [How can I make console.log show the current state of an object?](https://stackoverflow.com/questions/7389069/how-can-i-make-console-log-show-the-current-state-of-an-object) – Phil Jul 02 '20 at 05:06
  • @palaѕн added image – Derek W. Jul 02 '20 at 05:10
  • @MattJHoughton I am trying to sort an array of strings (which are formatted dates), but that shouldn't be a problem – Derek W. Jul 02 '20 at 05:10
  • Sorry, I meant a full array, as opposed to an empty one. If you do `console.log(JSON.stringify(res))`, you'll see what I mean. Also take note of that little blue _i_ in your console. In any case, the answer can be found in the linked duplicate – Phil Jul 02 '20 at 05:20
  • @Phil thanks! Took me a minute but using a for...of did the trick. Also I see what you mean with the blue i as well. Thanks again – Derek W. Jul 02 '20 at 05:24
  • Please add all information in readable form to your question - code or debugging output is shared best as text – Nico Haase Jul 02 '20 at 12:30

0 Answers0