One easy way to do it would be to move the code from the .then callback "outside" as follow :
const getEmailData = async (getExtention) => {
// return getExtention
try {
let res = await axios
.get(`https://getnada.com/api/v1/inboxes/${getExtention}`);
const getEmailCount = await res.data.msgs.length
if (parseInt(getEmailCount) >= 1) {
// console.log('Berhasil berhasil Hore')
const getDataEmail = await axios.get(
`https://getnada.com/api/v1/messages/html/${res.data.msgs[0].uid}`
)
if (getDataEmail) {
console.log('Data berhasil')
const getOTPEmail = await Promise.all(getDataEmail.data)
return getOTPEmail
} else {
console.log('Data Gagal')
}
}
} catch (e) {
getEmailData(getExtension);
}
}
Also, you will notice that this part const getEmailCount = await res.data.msgs.length probably doesn't work as you would expect because length isn't a promise.
But why isn't it working as is ?
Using .then is using a callback on the promise return by axios.get so your getEmailData function doesn't return anything. It is calling axios.get which is asynchronous and provide a callback once the promise has been resolved, and leaving.
Is there a way to make this work using .then ?
There is, with the following steps :
- initialize a Promise in getEmailData
- remove the await in front of axios.get call.
- call resolve from the initialized Promise in .then callback
Pseudo-Code :
const getEmailData = async (getExtension) => {
return new Promise((resolve) => {
axios.get().then((res) => {
resolve(res);
})
});
}
But it is way easier to write, easier to read and cleaner to use await, otherwise it's becoming a callback hell :)