0

I have this function that returns a result from a GET in an API (I am using an AWS Rest API, for contextualization):

const listUsers = async () => {
  const apiName = 'AdminQueries'
  const path = '/listUsers'
  const params = {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `${(await Auth.currentSession())
        .getAccessToken()
        .getJwtToken()}`,
    },
  }
  return await API.get(apiName, path, params)
}

And if i call the function to print on console, like:

console.log(listUsers())

I get an array on my console:

Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
Users: Array(42)
0: {Username: "00e534e3-08ee-4bc1-9d19-ab18208e3f94", Attributes: Array(5), UserCreateDate: "2021-09-06T10:05:35.537Z", UserLastModifiedDate: "2021-09-06T10:05:35.537Z", Enabled: true, …}
1: {Username: "05f4ce2e-4b57-48d5-9f5f-e18d250aefb4", Attributes: Array(6), UserCreateDate: "2021-09-10T19:45:32.002Z", UserLastModifiedDate: "2021-09-10T19:54:37.333Z", Enabled: true, …}
2: {Username: "06a78cc7-af6a-4fb6-975d-458c089b69a5", Attributes: Array(6), UserCreateDate: "2021-09-10T18:04:27.780Z", UserLastModifiedDate: "2021-09-10T18:04:27.780Z", Enabled: true, …}
3: {Username: "32652d77-e7a4-444a-9995-f8f50eb14633", Attributes: Array(6), UserCreateDate: "2021-09-06T15:48:24.897Z", UserLastModifiedDate: "2021-09-06T15:49:39.476Z", Enabled: true, …}
length: 42
__proto__: Array(0)
__proto__: Object

How do i map these users to show in an array? I tried but couldn't.

Henrique Monteiro
  • 107
  • 1
  • 1
  • 9
  • It's an async function use `console.log(await listUsers())` – Ankush Verma Sep 14 '21 at 19:24
  • Remove `async` and `await` in your `listUsers` function; you don't need it there. Now run `const users = await listUsers();` and `console.log(users)` from some async function. (to be clear: there's no escaping back to sync code; once you use async code, you stay async as you go up the function calls) also see here: https://jsfiddle.net/khrismuc/kpj204wL/ –  Sep 14 '21 at 19:25
  • @ChrisG if i remove the async await on the function body, it brokes it, cause the `.getAccessToken()` depends on it. Also i don't get how this solves my problem. I still can't map it... – Henrique Monteiro Sep 14 '21 at 19:33
  • @AnkushVerma if i do that, i get `Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)` – Henrique Monteiro Sep 14 '21 at 19:35
  • Right; I missed the 2nd await. Anyway, if you call `listUsers()` in a sync context, you will always get the promise, not the users array. You need to `await listUsers()` to get the array. You can use `await` in the top-level but you have to enable it or update node. Did you look at my fiddle...? It should make all of this clear. –  Sep 14 '21 at 19:35
  • @ChrisG as i said in the above comment, still doesn't work. I get that error. I am on React (actually NextJS), on a company-wide project, how could i enable this thing? I am not getting, actually. – Henrique Monteiro Sep 14 '21 at 19:36
  • Also note that this is the #1 beginner's JavaScript issue, which is why this exists: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron –  Sep 14 '21 at 19:37

2 Answers2

0

Your listUsers function is returning a promise. To get the response you can make use of something like this

const listUsers = async () => {
  const apiName = 'AdminQueries'
  const path = '/listUsers'
  const params = {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `${(await Auth.currentSession())
        .getAccessToken()
        .getJwtToken()}`,
    },
  }
  return await API.get(apiName, path, params)
}

**** update ****
const func = async () => {
   const response = await listUsers();
   console.log(response);
}

func();
Kritish Bhattarai
  • 1,501
  • 15
  • 20
  • Yes! This way i get an Array on the console. But i can't do func().map, or func.map. So how would i map it? – Henrique Monteiro Sep 14 '21 at 19:58
  • In that case, you can simply return your array instead of returning promise from `listUsers` function. – Kritish Bhattarai Sep 14 '21 at 20:04
  • but which array, man? i am not getting... if i call func(), this appears on the console: i.imgur.com/TB9O6tK.png If i don't call func(), it doesn't appear. But how can i show THIS array in my react component? I am not getting, you know? – Henrique Monteiro Sep 14 '21 at 20:08
  • since you wanted to use map, i assumed api responds with an array. if its correct, you can setState inside listUsers(), – Kritish Bhattarai Sep 14 '21 at 20:20
0
const listUsers = async () => {
      const apiName = 'AdminQueries'
      const path = '/listUsers'
      const params = {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `${(await Auth.currentSession())
            .getAccessToken()
            .getJwtToken()}`,
        },
      }
      return await API.get(apiName, path, params)
    }

    const func = async () => {
      const response = await listUsers();
      reponse.data?.map((item) => {
        console.log(item);
      })
    }
Danish
  • 47
  • 3