0

I just wanted to get random user data from some API then i used async function so that at last i can return person name array. Here is my code

const getPersonName = async () => {
  // Fake user Data api
  const response = await fetch("https://dummyjson.com/users");
  const data = await response.json();
  const firstName = data.users.map((currUser) => currUser.firstName);
  const lastName = data.users.map((currUser) => currUser.lastName);
  return [...firstName, ...lastName];
};

after creating the function i have to store the returning value into names variable then i tried this.

const names = async () => await getPersonName();

when i console.log(names) it is still giving me promise

i wanted to store like this const names = ['Some name','some name']

1 Answers1

0

If you want to call an async function at the top level, you can wrap your code in an async IIFE:

(async () => {
    const names = await getPersonName();
})();
yadejo
  • 1,910
  • 15
  • 26
  • 1
    Yes, but unless the environment has "top-level await" configured that code still needs to be wrapped in an async function which I think is what the OP was getting at. – Andy Sep 28 '22 at 11:42
  • if i will call the function like this then it will give me error like await cannot be used without async – Mohammed Raza Sep 28 '22 at 12:03
  • Modified my answer to meet your question. – yadejo Sep 28 '22 at 12:24