繁体   English   中英

为什么我的async fetch调用一直返回或退出到最外面的function,执行外面的function,然后继续执行里面的?

[英]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 的其余部分才会运行。

我的问题是:

  1. 是什么导致了这种行为? 我希望在继续使用 .onsubmit 处理程序之前运行整个 send_email 。
  2. 在完成 .onsubmit 事件中的后续代码之前,完成我在这里的目标的正确方法是什么,执行整个 send_email,包括 API fetch 调用?

感谢所有帮助,谢谢!

尝试使您的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM