具有非异步功能的Dart未来

时间:2020-06-01 11:32:31

标签: dart async-await

我正在使用Dart创建用于Firebase电话身份验证的功能。有两个函数getCredential和signIn。当使用try / catch块时,我不确定应该如何编码。非异步函数getCredential应该在try / catch块之外还是内部?

应将其编码为:

  // Sign in with phone
  Future signInWithPhoneNumber(String verificationId, String smsCode) async {
    AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    try {
      AuthResult result = await _auth.signInWithCredential(credential);
      FirebaseUser user = result.user;
      return user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

还是应该这样编码?

  // Sign in with phone
  Future signInWithPhoneNumber(String verificationId, String smsCode) async {
    try {
      AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: smsCode,
      );
      AuthResult result = await _auth.signInWithCredential(credential);
      FirebaseUser user = result.user;
      return user;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

如果编码为第二个选项,则try / catch仅适用于异步功能或两者都适用。例如,如果getCredential函数生成错误,是否会在catch块中捕获它?

1 个答案:

答案 0 :(得分:0)

是的,该catch可以处理在try块中引发的所有事件,这不是异步特定的。为了确认这一点,您可以编写一个在尝试开始时被调用的函数,例如:

// this is a function that throws
void doSomething(String param) {
   if (param == null) {
     throw FormatException('param can not be null'); 
   }
}


Future signInWithPhoneNumber(String verificationId, String smsCode) async {
  try {
    doSomething(null); // this will be caught
    AuthCredential credential = PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode,
    );
    AuthResult result = await _auth.signInWithCredential(credential);
    FirebaseUser user = result.user;
    return user;
  } catch (e) {
    print(e.toString()); // this prints 'FormatException: param can not be null'
    return null;
  }
}  

所以异步与是否捕获函数无关,因此最好使用第二个选项。