[英]How to save returned value to variable with async/await using axios?
So i have the following example: 所以我有以下示例:
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?
};
I can't get the response object into a variable, the promise doesn't resolve no matter what. 我无法将响应对象放入变量,promise不管如何都无法解决。 How should i do this?
我应该怎么做?
userApi().then(res => {
userList = res //also doesn't work
return res
})
console.log(userList)
You are trying to access a variable from within your function scope outside of the function. 您正在尝试从函数外部的函数范围内访问变量。 Try this instead and let me know if it worked.
试试这个,让我知道它是否有效。
const userApi = async () => { const res = await axios({ url: URL + 'getUserData', method: 'post', data: {message: 'getUserList'} }) return res.data }; let userList = []; some_other_function = async () => { userList = await userApi(); }
This should do it. 这应该做。
const userList = await userApi();
console.log(userList);
some_other_function = async () => {
const userList = await userApi()
console.log(userList)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.