У меня есть функция отправки
const onSubmit = async (creditCardInput) => {
const { navigation } = this.props;
this.setState({ submitted: true });
let creditCardToken;
try {
creditCardToken = await getCreditCardToken(creditCardInput);
if (creditCardToken.error) {
this.setState({ submitted: false});
return;
}
} catch (e) {
this.setState({ submitted: false });
return;
}
try {
const obj = await subscribeUser(creditCardToken);
console.log('returned obj', obj);
try {
const docRef = await this.db.collection("users").doc(this.user.email).set({
id: this.user.uid,
subscriptionId: obj.customerId,
active: true
});
console.log("Document written with ID: ", docRef);
this.navigateToScreen('HomeScreen');
} catch (e) {
console.log("Error adding document: ", e);
}
} catch (error) {
console.log('catch error', error);
this.setState({ submitted: false, error: SERVER_ERROR, message: error });
}
};
Это работает как подозревается - когда вызов this.db.collection завершается неудачно, реализуется перехват, означающий, что он выходит из системы «Ошибка добавления документа:», e см. Фрагмент коданиже
try {
const docRef = await this.db.collection("users").doc(this.user.email).set({
id: this.user.uid,
subscriptionId: obj.customerId,
active: true
});
console.log("Document written with ID: ", docRef);
this.navigateToScreen('HomeScreen');
} catch (e) {
console.log("Error adding document: ", e);
}
Однако, когда я реализую пользовательскую функцию подписки другим способом (см. ниже), я больше не использую try catch, а скорее. После ожидания внутренняя функция завершается сбоем, а внешний catchоператор выполнен, то есть выходит из системы console.log ('catch error', error);когда он должен выйти из системы console.log («Ошибка добавления документа:», ошибки);почему это? не должны ли они работать одинаково, то есть фрагмент кода выше и ниже должен работать одинаково, см. код ниже
await subscribeUser(creditCardToken).then((obj)=> {
this.db.collection("users").doc(this.user.email).set({
id: this.user.uid,
subscriptionId: obj.customerId,
active: true
}).then((docRef) => {
console.log("Document written with ID: ", docRef);
this.navigateToScreen('HomeScreen');
}).catch((errors) => {
console.log("Error adding document: ", errors);
});
}).catch((error) => {
console.log('catch error', error);
this.setState({ submitted: false message: error });
});
Просто добавленное примечание, когда this.db.collections успешно разрешает выполнение .thenкак это должно означать, что он выходит из системы с помощью console.log («Документ, написанный с ID:», docRef), однако, как я уже говорил, если он отклонен, выполняется внешний захват, а не внутренний захват
Также добавляется возвратк функции this.db.collection и удаление await не влияет на результат