【发布时间】:2021-06-08 17:59:26
【问题描述】:
我有一个简单的问题。我尝试在网上找到解决方案,但每次尝试都失败了。 我有这个代码:
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
}
当我像这样使用这个功能时:
const useFunction = getSideBarMenu1()
console.log('useFunction', useFunction)
控制台日志的结果是:
useFunction Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(100)
如何将 PromoseResult 保存在变量中? 谢谢大家!
【问题讨论】:
-
这是因为
getSideBarMenu1是一个异步函数。所以你需要用await getSideBarMenu1()调用它 -
意外的保留字“等待”是终端返回的内容。我正在为 VueJS 使用 vuexy 模板
-
您可以使用
.then()。一个 promise 只能在 async 函数中被 await 调用。所以你可以这样做getSideBarMenu1().then(res => console.log(res)).catch(err => console.log(err))
标签: javascript vue.js async-await