【问题标题】:Why do my code lines after await not get called?为什么等待后我的代码行没有被调用?
【发布时间】:2020-03-11 21:21:42
【问题描述】:

我对以下代码有疑问。 firebase.login 返回一个 Promise,我了解到,当我之前输入“await”时,Javascript 会等到 Promise 交付,然后继续下一行。I

但下一行似乎永远不会被触发。我究竟做错了什么?它也不会停在“调试器”标记处。

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

【问题讨论】:

  • 你在异步函数中吗?控制台中的任何错误?请发布一个可重现的问题。
  • 也许const user = await firebase.login(email, password); 这一行会返回错误,控制转移到catch(error) 块。
  • 我认为 OP 更有可能没有将其放入异步函数中并且出现语法错误,但没有更多信息无法确定
  • firebase.login 这是什么?,你能指出来源或文档吗?

标签: javascript reactjs asynchronous promise async-await


【解决方案1】:

firebase.login(); 调用返回的Promise 应包含在async 函数中(我们无法从您的 sn-p 中看到)。如 cmets 中所述,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);
  }
})();

【讨论】:

    【解决方案2】:

    解决方案:

    我从我的新英雄那里得到了解决方案:

    "提交按钮提交表单。

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

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

    之前执行此操作

    所以,我要做的就是插入“event.preventDefault”。在教程中使用了一个简单的按钮,它不会导致表单提交。我使用了引导提交按钮,这就是为什么我认为表单总是被提交的原因。

    【讨论】:

      猜你喜欢
      • 2020-07-02
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      相关资源
      最近更新 更多