-2

Whenever I try making fetch get api calls I am not able to save the result of it in my other JavaScript variables. either nothing happens or I get something like '[object Promise]'. What exactly am I doing wrong in this specific call and/or code?

users.js:

async function githubUsers() {
  let response = await fetch('https://api.github.com/users')
  let users = await response.json()
  console.log(users)
  return users
}

githubUsers()
let allUsers= githubUsers()
let UsersWidget = `
<div>
  <div>
    <p>Current Online users: ${allUsers}</p>
  </div>
</div>`

I have a main.js file where I call upon it:

main.js

document.writeln(UsersWidget);

and here is my index.html

<!DOCTYPE html>
<html>
<head>
    <title>Github users</title>
    <link href="css/tailwind.min.css" rel="stylesheet">
    <script type="text/javascript" src="js/users.js"></script>

</head>
<body class="bg-blue-500">
test
</body>
</html>

2 Answers2

1

You forgot to await the result of that Promise. Even if you dont explicitly return a Promise from githubUsers the return value is a Promise because it's an async function:

let allUsers = await githubUsers()

If you can't use await because not in the context of an async function, write this:

const allUsers = githubUsers().then(users => {
  return `
  <div>
    <div>
      <p>Current Online users: ${users}</p>
    </div>
  </div>`
});

In main.js:

allUsers.then(x => document.writeln(x));
Guerric P
  • 30,447
  • 6
  • 48
  • 86
1

You need an await enclosed in an IIFE as

(async () => {
    let allUsers = await githubUsers()
    let UsersWidget = `
    <div>
      <div>
        <p>Current Online users: ${allUsers}</p>
      </div>
    </div>`
})();

We want to wait for githubUsers before we can populate UsersWidget and as this invocation is not enclosed inside a context function, you need a surrounding IIFE

Saksham
  • 9,037
  • 7
  • 45
  • 73