0

I have a simple, question. I try to found a solution on web but every try failed. I have this code:

   const getSideBarMenu1 = async () => {
      let myArray = []
      await axios.get('https://jsonplaceholder.typicode.com/posts').then(res => {
        console.log('res1', res)
        myArray = res.data
      }).catch(err => console.log(err))
      console.log('myArray', myArray)
      return myArray
    }

And when I use this function like this:

 const useFunction = getSideBarMenu1()
    console.log('useFunction', useFunction)

the result of console log is:

useFunction Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(100)

How to save the PromoseResult inside a variable? Thank you everyone!

Alberto Torrisi
  • 85
  • 1
  • 10
  • It's because `getSideBarMenu1` is an Async function. So you need to call it with `await getSideBarMenu1()` – CyberEternal Jun 08 '21 at 09:44
  • Unexpected reserved word 'await' is what terminal return. I'm using vuexy template for VueJS – Alberto Torrisi Jun 08 '21 at 10:44
  • You can use `.then()`. A promise can be called by the await only within an async function. So you can do the following `getSideBarMenu1().then(res => console.log(res)).catch(err => console.log(err))` – CyberEternal Jun 08 '21 at 10:48

4 Answers4

1

You need to wait for the promise to fulfill, before accessing its result:

const useFunction = await getSideBarMenu1()
moustafa
  • 251
  • 2
  • 11
1

getSideBarMenu1 is async that returns a Promise, meaning you have to await it.

const useFunction = await getSideBarMenu1();

You can also use .then()

axtck
  • 3,707
  • 2
  • 10
  • 26
0

You can also return data directly from getSideBarMenu1 function:

const getSideBarMenu1 = async () => {
  const {data} = await axios.get('https://jsonplaceholder.typicode.com/posts')
  return data
}


const useFunction = await getSideBarMenu1()
Daniel
  • 2,621
  • 2
  • 18
  • 34
0

You forgot a little keyword here.

const useFunction = await getSideBarMenu1()
console.log('useFunction', useFunction)

article source: https://jasonwatmore.com/post/2020/04/30/vue-fetch-http-get-request-examples video source: https://www.youtube.com/watch?v=NHfyF0B4y8E

Furkan Gulsen
  • 1,384
  • 2
  • 12
  • 24