In NestJS, I have this async services called fetchUsers
and processUsers
async fetchUsers(type: string): Promise<UserResponse> {
try {
const result = await axios.get('/url')
return result;
} catch (err: any) {
console.log(err)
}
}
async processUsers(type: string): Promise<UserResponse> {
const data = await this.fetchUsers(type)
console.log('data', data)
return data;
}
The code above does not work:
- it prints the console log first, and then it go to the
fetchUsers
logic - it returns null because data is undefined
However, if I use fetchUsers
with promise, like this:
async processUsers(type: string): Promise<UserResponse> {
return this.fetchUsers(type).then((res) => {
console.log('data', data)
return data
})
}
then it will works, it will print the log first and then returns data.
What could be the reasons behind this behavior? Also it’s worth noting that other code like this in my project works just find, only this one have this weird behavior