цепочки ждут с .then и попробуют перехватить синтаксис - PullRequest
0 голосов
/ 08 октября 2019

У меня есть функция отправки

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 не влияет на результат

1 Ответ

0 голосов
/ 08 октября 2019

Есть два способа справиться с этим - преобразовать вашу функцию set в синтаксис async / await или return вашу функцию set в следующую функцию *1005* затем функции,Я покажу оба, но я предпочитаю второе, так как мне не нравится смешивать async / await с then / catch.

const tempThis = this
subscribeUser(creditCardToken).then((obj)=> {
  // RETURN this promise and you'll get it in the next then statement
  return tempThis.db.collection("users").doc(tempThis.user.email).set({
    id: tempThis.user.uid,
    subscriptionId: obj.customerId,
    active: true
  })
}).then((docRef) => {
  console.log("Document written with ID: ", docRef);
  this.navigateToScreen('HomeScreen');
}).catch((errors) => {
  // This will catch the errors from subscribeUser AND from the set function
  console.log("Error adding document: ", errors);
});

или использовать просто async / await

try {
  const obj = await subscribeUser(creditCardToken)
  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 (error) {
  // Handle your errors
}
...