Why do my code lines after await not get called?

点点圈 提交于 2020-03-16 09:14:45

问题


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

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);
    }
  }```

回答1:


The returned Promise from the firebase.login(); call should be wrapped within an async function (which we cannot see from your snippet). As mentioned in the comments it's possible that the catch is being triggered, in which case you should be gracefully handling the error.

// 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);
  }
})();



回答2:


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. It does this before reaching console.log("l2");"

So, everthing I had to do was insert "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.



来源:https://stackoverflow.com/questions/60618115/why-do-my-code-lines-after-await-not-get-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!