0

I have 2 promises with same "then" and "catch" conditions. How can I merge them into single promise based on a condition?

Promise 1

return new Promise((resolve, reject) => {
    abc.getDataFromServer(resp1)
        .then((result) => {
            .....
            resolve();
        })
        .catch((error) => {
            .....
            reject(error);
        });
});

Promise 2

return new Promise((resolve, reject) => {
    abc.getDataFromDB(resp2)
        .then((result) => {
            .....
            resolve();
        })
        .catch((error) => {
            .....
            reject(error);
        });
});

Required Promise Chaining

return new Promise((resolve, reject) => {
    if(condition){
       abc.getDataFromServer(resp)
    }else{
       abc.getDataFromDB(resp2)
    }
        .then((result) => {
            .....
            resolve();
        })
        .catch((error) => {
            .....
            reject(error);
        });
});

What is the best way to achieve this?

Abhinav Tyagi
  • 5,158
  • 3
  • 30
  • 60

1 Answers1

2

Use the conditional operator, based on the condition, to determine the initial Promise, and then call .then and .catch on it. Also, avoid the explicit Promise construction antipattern:

return (condition ? abc.getDataFromServer(resp) : abc.getDataFromDB(resp2))
  .then((result) => {
      .....
      // instead of resolve(someTransformedResult):
      return someTransformedResult;
  })
  .catch((error) => {
      .....
      // instead of reject(error):
      throw error;
  });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • if I can't avoid explicit Promise construction, then? – Abhinav Tyagi Jan 09 '19 at 05:06
  • 1
    You *can* avoid it, given the code in your question, because you can already call `.then` directly on the Promises returned by `getDataFromServer` / `getDataFromDB`. They're thenables, so you don't need to construct a separate Promise to handle them. – CertainPerformance Jan 09 '19 at 05:07