Search code examples
javascriptpromisechaining

chain promise to function


I have a function

const func = () => server.insertPatientSurveyQuestionToDataBase(Store.getPatientID(), SurveyNumber, Store.getPatientQuestion())

that is called.

after this, there is a function:

const promise = 
  server.GetPatientHistoryData(Store.getPatientID())
    .then(
      response => Dispatcher.dispatch({
        actionType: Constants.CHANGE_PATIENT_HISTORY,
        payload:response}))

    .catch(error => {console.log(error)});

I do this, which i believe should work:

func().then(response => promise())

but it returns a cannot read property then of undefined. I was under the impression this could work. How do I chain a function to a promise?


Solution

  • It causes this error because func doesn't return a promise. If this part is a promise:

    server.insertPatientSurveyQuestionToDataBase(Store.getPatientID(), SurveyNumber, Store.getPatientQuestion());
    

    You need to return it inside of func:

    const func = () => {
        return server.insertPatientSurveyQuestionToDataBase(Store.getPatientID(), SurveyNumber, Store.getPatientQuestion());
    };
    

    Then you can safely use it like this:

    func().then(response => promise());