我需要调用结果(来自函数的数组)在函数外部调用
我的代码看起来像这样
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: ...
}
]
这是我对结果进行硬编码的方式,
const it = [
{
name: 'Good'
},
{
name: 'Bad'
},
{
name: 'Handsome'
}
]
是否有动态填充it变量的想法?
更新
我没有足够的声誉回答我自己的问题,这就是我重构代码以使其工作的方式
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'
}
]
}
任何想要使这些代码更好的想法都值得赞赏。我错过了什么,或者我是否正确使用此代码?
答案 0 :(得分:1)
并不完全清楚您提出的问题,但如果您要问如何更改items
变量,请将其更改为let
而不是const
,将您的代码更改为:
.then((response) => {
cheats = response.data;
console.log(cheats, 'yeah')//results[Good, Bad]
items = response.data.map(item => ({ name: item }));
return cheats
})