I'm fetching data from server using axios.post method but it returns early .I have used async and await but data is not updated
apiService.js
export const getAppAuthUser = async (page, authorizedType) => {
await axios.post(APIURL.apiURL, JSON.stringify({
page: page,
authorized: authorizedType
}), {
headers: {
'Content-Type': 'application/json'
}
}).then(res => {
console.log(res);
return res.data;
}).catch(err => {
console.log(err);
});
}
component.js
import * as Users from '../api/apiService';
class User extends Component {
sortedInfo = {};
componentDidMount() {
this.data=Users.getAppAuthUser(1,true);
console.log(this.data);
}
}
when I console it return Promise {}
Please help
That's what async
functions do: they return promises. async/await
exists to make the syntax for working with promises easier, but it does not change the fact that promises are involved. To get the value inside the promise, you'll need to use the promise's .then
method, or put your code in an async function and await its result.
You also have a problem in your getAppAuthUser function that you're not returning anything, and so the promise will resolve to undefined. It's a lot easier to make this kind of problem when you're mixing the .then
style with the async/await
style. I'd strongly recommend just picking one style and using that consistently.
export const getAppAuthUser = async (page, authorizedType) => {
try {
const res = await axios.post(APIURL.apiURL, JSON.stringify({
page: page,
authorized: authorizedType
}), {
headers: {
'Content-Type': 'application/json'
}
})
console.log(res);
return res.data;
} catch (err) {
console.log(err);
}
}
import * as Users from '../api/apiService';
class User extends Component {
sortedInfo = {};
async componentDidMount() {
this.data = await Users.getAppAuthUser(1,true);
console.log(this.data);
}
}
JavaScript is asynchronous, we can't use like this this.data=Users.getAppAuthUser(1,true)
if you wish to use same like this then use async-await
like this async componentDidMount() { this.data= await Users.getAppAuthUser(1,true); console.log(this.data); }
async componentDidMount() { this.data= await Users.getAppAuthUser(1,true); console.log(this.data); }
Or you can use promise like this Users.getAppAuthUser(1,true).then(data=>{ console.log(data); })
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.