0

I need to call the result(array from a function) Called outside the function

My Code look likes this

import axios from 'axios'
var cheats
(() => {
  axios.get('api/cheats/getcheaternames')
  .then((response) => {
    cheats = response.data
    console.log(cheats, 'yeah')//results[Good, Bad]
    return cheats
  })
  .catch((error) => {
     console.log(error, 'err')
  })
})()

const it = [
    {
        name: ...
    }
]

This is how I hardcode the result,

const it = [
   {
      name: 'Good'
   },
   {
      name: 'Bad'
   },
   {
      name: 'Handsome'
   }
]

Any idea to dynamically populate the it variable?

Update

I have no enough reputation to answer my own question, here it is how I refactor my code to make it work

import axios from 'axios'

var cheats
var it = []
let myFirstPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
       resolve(axios.get('api/cheats/getcheaternames')
        .then((response) => {
            cheats = response.data
            return cheats
        })
        .catch((error) => {
            console.log(error, 'err')
        }))
    }, 250)
})

myFirstPromise.then((successMessage) => {
// for (var i = 0; i < successMessage.length; i++) {
//     it.push({name: i})
// }
   for (const value of successMessage) {
      it.push({name: value})
   }
})

export default {
  items: [
    {
        name: 'Dashboard',
        url: '/dashboard',
        icon: 'icon-speedometer',
        badge: {
            variant: 'primary',
            text: 'Cheaters'
        }
    },
    {
        title: true,
        name: 'Elements',
        class: '',
        wrapper: {
            element: '',
            attributes: {}
        }
    },
    {
        name: 'Cheats',
        url: '/components',
        icon: 'icon-puzzle',
        children: it
    },
    {
        name: 'Angular Version',
        url: 'https://angular.herokuapp.com/',
        icon: 'icon-cloud-download',
        class: 'mt-auto',
        variant: 'success'
    }
]

}

Any idea to make this code better is appreciated. Am I missing something or am I doing right with this code?

Ian Adem
  • 119
  • 2
  • 14

1 Answers1

1

Not entirely clear what you're asking, but if you're asking how to change the items variable, change it to have let instead of const and change your code to:

.then((response) => {
    cheats = response.data;
    console.log(cheats, 'yeah')//results[Good, Bad]
    items = response.data.map(item => ({ name: item }));
    return cheats
 })
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • I need to call response.data value outside the function, in this case, in items constant – Ian Adem Nov 24 '17 at 07:42
  • @IanAdem The `items` variable (it's not a constant if its value changes) _will_ contain the values, but only _after_ the request has completed. It looks like you need to familiarize yourself with how to work with asynchrony. Please refer to the link at the top of this page. – JLRishe Nov 24 '17 at 08:02