[英]Why does my async fetch call return or exit all the way to the most outer function, execute the outer function, THEN continue executing the inner one?
我的代码是这样的:
document.querySelector('#compose-form').onsubmit = () => {
const success = send_email();
if (success === true) {
setTimeout(() => {load_mailbox('sent'); }, 100);
}
return false;
}
send_email function:
async function send_email() {
// some code here
const response = await fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body
})
})
// more code here
}
当 .onsubmit 被执行时,send_email 执行并顺利运行,直到我们到达 fetch 调用。 通过调试器运行,当整个 fetch 代码块执行时,下一步是不继续通过 send_email。 相反,.onsubmit 事件的其余部分在没有为我的 const 成功分配适当的值的情况下执行,并且只有在完成后,send_email 的其余部分才会运行。
我的问题是:
感谢所有帮助,谢谢!
尝试使您的 onsubmit function 异步,然后等待send_email()
的结果:
document.querySelector('#compose-form').onsubmit = async () => {
const success = await send_email();
if (success === true) {
setTimeout(() => {load_mailbox('sent'); }, 100);
}
return false;
}
如果您不等待send_email
的结果,它将继续同步执行该 function 的代码的 rest。
然后,您实际上需要从send_email()
返回一些东西。 我假设这是在// more code here
部分中,但从您的代码中不清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.