【问题标题】:Why does my code not execute after await statement? [duplicate]为什么我的代码在 await 语句后不执行? [复制]
【发布时间】:2020-06-23 10:59:47
【问题描述】:

我有一个使用 google firebase 进行身份验证的 javascript react 应用程序的问题.....“等待”之后的代码没有执行,并且 chrome 做了一些奇怪的重新加载(似乎)。

我已尝试重建本教程中的内容:

https://www.youtube.com/watch?v=K_wZCW6wXIo

https://github.com/mehulmpt/firebase-react-hooks

这是我的 Login.js

...
....
      <Form.Group controlId="formBasicPassword">
        <Form.Label>Password</Form.Label>
        <Form.Control
          type="password"
          placeholder="Password"
          onChange={e => setPassword(e.target.value)}
        />
      </Form.Group>
      <Form.Group controlId="formBasicCheckbox">
        <Form.Check type="checkbox" label="Check me out" />
      </Form.Group>
      <Button variant="primary" type="submit" onClick={login}>
        Submit
      </Button>
    </Form>
  );

async function login() {
    try {
      console.log("l1");
      await firebase.login(email, password);
      console.log("l2");
      debugger;
      props.history.replace("/impressum");
    } catch (error) {
      console.log("l3");
      alert(error.message);
    }
  }

这里还有 firebase.js 辅助类:

class Firebase {
  constructor() {
    app.initializeApp(config);
    this.auth = app.auth();
    this.db = app.firestore();
  }

  login(email, password) {
    return this.auth.signInWithEmailAndPassword(email, password);
  }
...
...

当我使用“npm start”(它是一个反应应用程序)运行应用程序时,打开控制台和调试器的 Chrome 开发人员窗口,然后点击登录表单的“提交”按钮,我看到了“l1 " 在控制台中记录输出大约半秒。然后开发者窗口似乎重新加载,控制台似乎被重置,“l1”消失了,“l2”,“l3”根本没有出现。并且调试器不会在断点处停止,也不会执行到“/impressum”的重定向。

我现在很绝望。我尝试了数百种我的异步、等待、然后捕获的变体……我什至不知道我的代码是否错误,或者我的 chrome 是否有问题(但在 Firefox 中也是如此)。

希望你能给点提示。

【问题讨论】:

  • 请使用您在此处提供的新信息编辑您现有的相同问题,而不是提出新问题。或者,您可以删除旧问题并投票重新打开此问题。

标签: javascript reactjs firebase promise async-await


【解决方案1】:

浏览器端 JavaScript 程序在网页上下文中运行。

提交按钮提交表单。

提交表单后,浏览器会导航到新网页。

由于运行 JS 程序的页面已被导航离开,该 JS 程序退出。它在到达 console.log("l2");

之前执行此操作

你可能想prevent the default behaviour of the submit button

【讨论】:

  • 嗨昆汀,我不知道你能不能读到这篇文章,因为我的帖子已关闭,但我爱你。数小时的绝望,而不仅仅是“event.preventDefault()”。疯狂的。非常感谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 2017-07-02
相关资源
最近更新 更多