如何让活动在承诺中等待,直到它运行



在向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);
});
};

此时,从startend的部分必须在步骤3之后(按钮事件之后(执行。

startend必须等待按钮事件的发生。

我该怎么做?

您试图在没有用户参与的情况下做太多事情。signInWithPhoneNumberPromise应解决显示确认请求页面的问题,并停止。它完成了。下一步是由用户提交确认号码。

所以,它看起来像

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

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

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

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

并在步骤3 的点击中调用上面的函数

您应该将auth代码确认转移到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);
});
};

最新更新