I have an async function with a request (superagent) in it. Every time the response from the request comes back, the whole function is resolved immidiately. How can I avoid this behaviour? :/
getToken: async () => {
await request
.post('https://tokenAdress')
.field('client_id', process.env.CLIENT_ID)
.field('client_secret', process.env.CLIENT_SECRET)
.field('grant_type', 'client_credentials')
.then( (response) => {
// do some stuff with response
return resultOfStuffDone;
}).catch( err => {
throw new Error(errorMessages.couldNotGetToken);
})
}
and ...
async () => {
let bla = await ApiEndpoints.getToken();
console.log(bla); // undefined
}
Would be appreciate if someone could help.
getToken: async () => {
let response = await request
.post('https://tokenAdress')
.field('client_id', process.env.CLIENT_ID)
.field('client_secret', process.env.CLIENT_SECRET)
.field('grant_type', 'client_credentials')
.catch( err => {
throw new Error(errorMessages.couldNotGetToken);
})
if(response !== undefined){
//do something
return resultOfStuffDone
}
}
When you use await the value can be assigned to a variable instead of using then.