简体   繁体   English

为什么在 await 之后我的代码行没有被调用?

[英]Why do my code lines after await not get called?

I have a problem with the following code.我对以下代码有问题。 The firebase.login returns a Promise and I learned that, when I put "await" before, Javascript waits until the Promise delivers and then continues with the next line.I firebase.login 返回一个 Promise,我了解到,当我之前放置“await”时,Javascript 会等到 Promise 交付,然后继续下一行。我

But the next line(s) seem never to be triggered.但是下一行似乎永远不会被触发。 What am I doing wrong?我究竟做错了什么? It also does not stop at the "debugger" mark.它也不会停留在“调试器”标记处。

    try {
      const user = await firebase.login(email, password);
      console.log("l1: ", user);
      debugger;
      props.history.replace("/impressum");
    } catch (error) {
      alert(error.message);
    }
  }```

The returned Promise from the firebase.login();firebase.login();返回的Promise firebase.login(); call should be wrapped within an async function (which we cannot see from your snippet). call 应该包含在async函数中(我们无法从您的代码段中看到)。 As mentioned in the comments it's possible that the catch is being triggered, in which case you should be gracefully handling the error.正如评论中提到的,有可能触发了catch ,在这种情况下,您应该优雅地处理错误。

 // mock the firebase login Promise const firebase = { async login(email, password) { return { email }; } }; (async() => { try { const [email, password] = [ 'joe.bloggs@example.com', 'password123', ]; const user = await firebase.login(email, password); console.log(user); } catch (err) { console.error(err); } })();

Solution:解决方案:

I got the solution from my new hero:我从我的新英雄那里得到了解决方案:

"Submit buttons submit forms. “提交按钮提交表单。

When a form is submitted, the browser navigates to a new web page.提交表单后,浏览器会导航到新网页。

Since the page the JS program was running in has been navigated away from, that JS program exits.由于运行 JS 程序的页面已被导航离开,因此该 JS 程序退出。 It does this before reaching console.log("l2");"它在到达 console.log("l2"); 之前执行此操作

So, everthing I had to do was insert "event.preventDefault".所以,我所要做的就是插入“event.preventDefault”。 In the tutorial the used a simple Button, that does not cause the form to submit.在教程中使用了一个简单的按钮,它不会导致表单提交。 I used a bootstrap submit-button und thats why I think the form was always submitted.我使用了引导提交按钮,这就是为什么我认为表单总是被提交。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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