Possible to set window.onload from within .then() of Promise?

Hey,

I’m trying to set some variables by making calls to my server and getting those values from the client-side. This is what I have:

var count = 0;
var nRepos = 0;

requestRepoNames().then(async (repoNames) => {
  nRepos = repoNames.length;
  for (let i = 0; i < repoNames.length; i++) {
    console.log(repoNames[i]);
    count += await requestCommitCount(repoNames[i]);
    console.log(count);
  }
  window.onload = () => {
    document.getElementById(
      "git-stats"
    ).innerHTML = `Haad has made ${count} commits in ${nRepos} repositories since August, 2022`;
  };
});

This doesn’t change the element though, I already made sure that there was no spelling error in the “git-stats” id. Any ideas on why the window is not getting updated?

Hi there!

The issue lies in where the window.onload event is being set. You’re defining window.onload inside the requestRepoNames().then() block, which executes asynchronously and only after the server call resolves. If the page has already loaded by the time the server call resolves, window.onload will not trigger because it’s a one-time event that occurs when the page initially finishes loading.

Instead of setting the window.onload event, directly update the element inside the .then() block once the values are resolved.

1 Like

Jazakumullah Khairan, that worked.

1 Like

Yahdikumullah. Happy Coding.