0
console.log(1)
console.log(2)
console.log(3)
console.log(4)
console.log(5)

async function getUsers(){
  let res = await  fetch('https://api.github.com/users')
  let finalRes = await res.json()

  console.log(finalRes)
}
getUsers()


console.log(6)
console.log(7)

In the above code i am trying to execute getUsers() function between console.log(5) and console.log(6), however in the output i am getting the output of getUsers func after console.log(7) . Is there anything i am doing wrong or what needs to be done if i want the getUsers o/p between console.log 5 & 6

Nagaraj
  • 13
  • 5

1 Answers1

3

You need to wait for the getUsers() function to finish. Currently you call it as if it were a plain function.

To do that, assuming the surrounding code is in a non-async context, you need to wrap the code in an async function:

async function getUsers(){
  let res = await  fetch('https://api.github.com/users')
  let finalRes = await res.json()

  console.log(finalRes)
}
(async () => {await getUsers(); console.log(6);})();
Pointy
  • 371,531
  • 55
  • 528
  • 584