【问题标题】:How can I keep the event waiting in the promise until it runs?如何让事件在承诺中等待直到它运行?
【发布时间】:2020-02-24 06:12:56
【问题描述】:

正在向firebase发送字符认证。

代码流程是...

  1. 用户输入电话号码并点击按钮
  2. 将值发送到服务器并以文本形式发送验证码
  3. 用户输入验证码并点击按钮
  4. 认证码值判别

在第二步中,按下按钮将执行signIn()即代码。

 const signIn = () => {
    auth
      .signInWithPhoneNumber(mobileNum, appVerifier)
      .then(function(confirmationResult) {

        //start

        window.confirmationResult = confirmationResult;

        confirmationResult
          .confirm(authCode)
          .then(function(result) {
            var user = result.user;
          })
          .catch(function(error) {
          });

        //end
      })
      .catch(function(error) {
        console.log(error);
      });
  };

此时start到end的部分必须在第3步之后(按钮事件之后)执行。

start 中的end 必须等待按钮事件发生。

我该怎么做?

【问题讨论】:

  • 您可以将//end部分移动到内部调用的.then中。
  • @Jai 但是我只能在单击按钮时允许 then 运行吗?
  • 看起来你想暂停里面的执行。 confirm 通话可以暂停。
  • @Jai authCode 是用户必须输入的值,无法判断是否存在。只能在按钮事件按下时执行。有什么我弄错了吗?

标签: javascript reactjs firebase


【解决方案1】:

您试图在没有用户参与的情况下做太多事情。 signInWithPhoneNumber Promise 应该解析为显示确认请求页面,然后停止。完成。下一步由用户提交确认号。

原来如此

  1. 事件处理程序 1 提交电话号码,然后解析显示确认输入屏幕
  2. 事件处理程序 2 将确认号提交给身份验证函数,然后解析更新用户并显示欢迎屏幕。

Promise 可用于管理计算机进程,而不是用户进程。您不能使用 Promise 来等待用户。您需要提供他们可以触发的事件处理程序以继续流程的下一步。

【讨论】:

  • 谢谢!迈克尔·兰迪斯。我解决了这个问题!
  • 太棒了!很高兴为您提供帮助!
【解决方案2】:

将下一个代码移动到另一个函数:

confirmationResult
          .confirm(authCode)
          .then(function(result) {
            var user = result.user;
          })
          .catch(function(error) {
          });

在第三步的onClick里面调用上面的函数

【讨论】:

    【解决方案3】:

    你应该把验证码确认移到promise链的左边,所以这一切都是按顺序完成的,一旦两个promise都完成了你就可以执行代码,像这样:

    
        const signIn = () => {
            auth
              .signInWithPhoneNumber(mobileNum, appVerifier)
              .then(function(confirmationResult) {
                window.confirmationResult = confirmationResult;
                return confirmationResult.confirm(authCode);
              })
              .then(function(result) {
                var user = result.user;
                // end here, auth code has been confirmed and you have access to user
              })
              .catch(function(error) {
                // this will catch errors in either "signInWithPhoneNumber" or "confirmationResult.confirm"
                console.log(error);
              });
          };
    
    

    【讨论】:

    • 但是,一旦第二阶段完成,此代码将运行到最后,无法进入第三阶段。我想要的是只有在单击按钮时才执行从头到尾的代码。我说错了吗?我很抱歉我的英语不好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    相关资源
    最近更新 更多