如何使用axios使用async / await将返回值保存到变量中?

问题描述 投票:0回答:1

所以我有以下示例:

const userApi = async () => {
 const res = await axios({
    url: URL + 'getUserData',
    method: 'post', 
    data: {message: 'getUserList'}
})
 return res.data
};





some_other_function = () => {
const userList = []
userList = userApi().then(res => {
  // console.log(res) works here but i need to get the response data outside...
   return res
 })
console.log(userList) // It's still a promise... Why?

我无法将响应对象放入变量,无论如何,promise都无法解析。我应该怎么做?

userApi().then(res => {
    userList = res //also doesn't work
    return res

})

console.log(userList)
javascript asynchronous async-await response
1个回答
0
投票

您正在尝试从函数外部的函数范围内访问变量。试试这个,让我知道它是否有效。

const userApi = async () => {
 const res = await axios({
    url: URL + 'getUserData',
    method: 'post', 
    data: {message: 'getUserList'}
})
 return res.data
};

let userList = []; 
some_other_function = () => {
userList = userApi().then(res => {
  // console.log(res) works here but i need to get the response data outside...
   return res
 })
 
console.log(userList) // It's still a promise... Why?
© www.soinside.com 2019 - 2024. All rights reserved.