I'm having issue in Promises in Javascript. one of my promise is returning undefined value but i have returned with resolve . heres the code

console.log("Before");

getUser(1)
  .then((user) => getRepositories(user.gitHubUsername))
  .then((repos) => {getCommits(repos[0]);})
  .then((commits) => {console.log("commits: ", commits);})
  .catch((err) => console.log("Error: ", err.message));

console.log("After");

function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Reading a user from a database...");
      resolve({ id: id, gitHubUsername: "mosh" });
    }, 2000);
  });
}

function getRepositories(username) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Calling GitHub API...");
      resolve(["repo1", "repo2", "repo3"]);
    }, 2000);
  });
}

function getCommits(repo) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Calling GitHub API...");
      resolve("commit");
    }, 2000);
  });
}

now here evey function which is chained is contains a promise which is resolving something i.e username, array etc. but when i run this code on the console it displays commnits : undefined

you can see it in this attached image

29 thoughts on “I'm having issue in Promises in Javascript. one of my promise is returning undefined value but i have returned with resolve . heres the code”

Leave a Comment