Цепочка двух обещаний - PullRequest
0 голосов
/ 01 марта 2019

У меня есть два обещания

    const promise_1 = this.connection.insertPatientToDataBase(Store.getPotentialPatientID())
      .then(ting => {
        console.log(ting);
        Dispatcher.dispatch({
        actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
        payload: ting.data.password
      })})
      .catch(error => {console.log(error)});

    const promise_2 = this.connection.getAllPatientData()
      .then( function(response) {
        console.log("Dispatrinc a new server call")
        console.log(response.data)
       Dispatcher.dispatch({
        actionType: Constants.CHANGE_ALL_PATIENTS,
        payload: response.data
      })})
      .catch(error => console.log(error))


      console.log("Done");
  }

: первое из них отправит некоторые данные на сервер, а второе запросит данные для повторной загрузки нового списка.Второй зависит от первого.Проблема в том, что первое обещание выполняется после.Второе обещание выполняется первым.Как я могу связать эти два обещания вместе, так что обещание 2 ждет обещание 1?

Ответы [ 4 ]

0 голосов
/ 01 марта 2019

Если обе функции не связаны, но обещание_1 должно быть разрешено первым, чтобы существующий пациент существовал, вы можете просто заключить создание обещания в функцию и вызывать создание обещания_2 только тогда, когда разрешается обещание_1:

const promise_1 = () => this.connection.insertPatientToDataBase(Store.getPotentialPatientID())
  .then(ting => {
    console.log(ting);
    Dispatcher.dispatch({
    actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
    payload: ting.data.password
  })})
  .catch(error => {console.log(error)});

const promise_2 = () => this.connection.getAllPatientData()
  .then( function(response) {
    console.log("Dispatrinc a new server call")
    console.log(response.data)
   Dispatcher.dispatch({
    actionType: Constants.CHANGE_ALL_PATIENTS,
    payload: response.data
  })})
  .catch(error => console.log(error));

  promise_1().then( response => promise_2());

Если обещание обещает, что обещание будет выполнено по обещанию обещания_1, например, если оно будет возвращать идентификатор пациента и вам нужен этот идентификатор, чтобы запустить обещание_2, и после обоих разрешений должен быть доступен только результат обещания_2, то вы можете изменить приведенное выше крошечноебит для передачи параметра:

const promise_1 = () => this.connection.insertPatientToDataBase(Store.getPotentialPatientID())
      .then(ting => {
        console.log(ting);
        Dispatcher.dispatch({
        actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
        payload: ting.data.password
      })})
      .catch(error => {console.log(error)});

const promise_2 = patient_id => this.connection.getAllPatientData( patient_id )
      .then( function(response) {
        console.log("Dispatrinc a new server call")
        console.log(response.data)
       Dispatcher.dispatch({
        actionType: Constants.CHANGE_ALL_PATIENTS,
        payload: response.data
      })})
      .catch(error => console.log(error));

promise_1()
  .then( patient_id => promise_2( patient_id ))
  .then( patient_data => {
    // handle patient data.
  });

Вы также можете реструктурировать все в более элементарные функции, чтобы у каждого обещания была одна конкретная цель, чтобы вы могли связать их все вместе.Если вы вложите структуру по-разному, вы даже можете сохранить все ответы и вернуть все потом в конце.

const create_patient_id = () => this.connection.insertPatientToDataBase(Store.getPotentialPatientID());

const create_patient = patient_id => Dispatcher.dispatch({
    actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
    payload: patient_id.data.password
});

const get_patients = () => this.connection.getAllPatientData();

const update_patients = patients => Dispatcher.dispatch({
    actionType: Constants.CHANGE_ALL_PATIENTS,
    payload: patients.data
})

const workflow = () => create_patient_id()
  .then( create_patient );
  .then( get_patients )
  .then( update_patients );

 workflow();
0 голосов
/ 01 марта 2019

При использовании then вы связываете обещания, создавая следующее в предыдущем преобразователе:

const promise_1 = this.connection.insertPatientToDataBase(Store.getPotentialPatientID())
  .then(ting => {
    console.log(ting);

    Dispatcher.dispatch({
      actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
      payload: ting.data.password
    });

    return this.connection.getAllPatientData();
  })
  .then(response => {
    console.log("Dispatrinc a new server call");
    console.log(response.data);

    Dispatcher.dispatch({
      actionType: Constants.CHANGE_ALL_PATIENTS,
      payload: response.data
    });
  })
  .catch(error => {console.log(error)});

с асинхронным ожиданием это может быть проще для глаз:

async insertAndGet() {
  try {
    const ting = await this.connection.insertPatientToDataBase(Store.getPotentialPatientID());

    console.log(ting);

    Dispatcher.dispatch({
      actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
      payload: ting.data.password
    };

    const response = await this.connection.getAllPatientData();

    console.log("Dispatrinc a new server call");
    console.log(response.data);

    Dispatcher.dispatch({
      actionType: Constants.CHANGE_ALL_PATIENTS,
      payload: response.data
    })};
  } catch (error) {
    console.log(error);
  }
}
0 голосов
/ 01 марта 2019
Promise1()
  .then(response => Promise2(response))
  .catch(err => {
    // do something with error
  });

Это ждет, пока первое обещание не будет разрешено, затем вызывает второе обещание с результатом.Вам не нужно передавать результат, если он вам не нужен .then(() => Promise2()).Если Promise1 терпит неудачу, то Promise2 никогда не вызывается.

Примечание: Очевидно, я не был достаточно многословен в своем первоначальном ответе, поэтому давайте разберем его немного лучше.

Во-первых, оберните ваши обещанные вызовы, чтобы вы могли предоставить дополнительную функциональность каждому:

class MyCustomClass {
  createNewPatient() { // maybe you pass it in? maybe it's always there?
    // Guessing Store is outside the class, but available
    return this.connection.insertPatientToDataBase(Store.getPotentialPatientID())
      .then(ting => {
        console.log(ting);
        // Guessing Dispatcher and Constants are outside the class, but available
        Dispatcher.dispatch({
          actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
          payload: ting.data.password
        });
      })
      .catch(error => {console.log(error)});
  }

  reloadResults() {
    return this.connection.getAllPatientData()
      .then( function(response) {
        console.log("Dispatrinc a new server call")
        console.log(response.data)
        // Guessing Dispatcher and Constants are outside the class, but available
        Dispatcher.dispatch({
          actionType: Constants.CHANGE_ALL_PATIENTS,
          payload: response.data
        });
      })
      .catch(error => {console.log(error)});
  }

  // What you seem to be looking for
  createAndReload() {
    return this.createNewPatient()
      .then(() => this.reloadResults())
      .then(() => {
        console.log('done');
      });
  }
}
0 голосов
/ 01 марта 2019

Вы можете просто переместить второй Promise в раздел then первого.Если первое обещание не выполнено, второе не будет выполнено, если оно выполнится успешно - второе начнется.Код будет выглядеть примерно так:

const promise_1 = this.connection.insertPatientToDataBase(Store.getPotentialPatientID())
  .then(ting => {
    console.log(ting);
    Dispatcher.dispatch({
      actionType: Constants.CHANGE_POTENTIAL_PATIENT_PASSWORD,
      payload: ting.data.password
    });
    const promise_2 = this.connection.getAllPatientData()
      .then(response => {
        console.log("Dispatrinc a new server call");
        console.log(response.data);
        Dispatcher.dispatch({
          actionType: Constants.CHANGE_ALL_PATIENTS,
          payload: response.data
        });
    })
    .catch(console.log);
  })
  .catch(console.log);

  console.log("Done");
}

Вы также можете связать Promises, передавая результаты от одного then к другому следующим образом:

SomePromiseFunc().then(result1 => SomeOtherPromiseFunc(result1)).then(result2=> doSmth(result2)).catch();

Этот способ может быть проще, есливы хотите использовать результат 1-го Promise внутри второго или если логика catch одинакова для них обоих.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...