嗨,我在这里遇到了一些问题,我想在获取 getnada 电子邮件上的目标内容后返回结果,但它总是返回未定义,有人可以在这里帮助我。
const getEmailData = async (getExtention) => {
// return getExtention
await axios
.get(`https://getnada.com/api/v1/inboxes/${getExtention}`)
.then(async (res) => {
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(() => {
getEmailData(getExtention)
})
}
这是我获取我想要获取的内容的过程代码
但是在我返回 getOTPEmail
之后它总是未定义的
我声明的结果是这样的
const getDataOTP = await getEmailData(getExtention)
console.log(getDataOTP)
有人能解释一下这段代码有什么问题吗?
答案 0 :(得分:1)
一种简单的方法是将代码从 .then
回调“外部”移动,如下所示:
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);
}
}
此外,您会注意到这部分 const getEmailCount = await res.data.msgs.length
可能不像您预期的那样工作,因为长度不是承诺。
但为什么它不能正常工作?
使用 .then
是在 axios.get
的承诺返回上使用回调,因此您的 getEmailData
函数不会返回任何内容。它正在调用 axios.get
,它是异步的,并在承诺解决后提供回调,然后离开。
有没有办法使用 .then 来完成这项工作?
有,步骤如下:
getEmailData
中初始化 Promiseawait
调用前的 axios.get
。resolve
回调中初始化的 Promise 调用 .then
伪代码:
const getEmailData = async (getExtension) => {
return new Promise((resolve) => {
axios.get().then((res) => {
resolve(res);
})
});
}
但是使用 await
更容易编写、更容易阅读和更干净,否则它就会变成回调地狱:)
答案 1 :(得分:1)
我认为错误在这里
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')
}
因为您在 if 语句中定义了 'getDataEmail' 变量,并且您想在它之外使用它。 所以,我认为你必须这样做
let getDataEmail ;
if (parseInt(getEmailCount) >= 1) {
// console.log('Berhasil berhasil Hore')
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')
}