0

I have nested promise calls structure as follow:

validateUser()
.then(() => {
  getUserInformation()
  .then((userInformation) => {
    Promise.all([
        getUserDebitAccounts(userInformation), 
        getUserCreditAccounts(userInformation)
    ])
    .then(([drAcc, crAcc]) => {
        //do something
    })
  })
})
.catch(error => {
  callback(error);
});

First of all is there a way to simplify these nested calls? As you can see they are structure as per dependency. So this is a most logical way I came up.

Second can I use catch at end to catch all the rejects on all above call. Do I have to add separate catch for each calls?

Third I want to write a mocha test what level of Promise mocking I have to do for these methods some outline will be helpful.

Any suggestion?

αƞjiβ
  • 3,056
  • 14
  • 58
  • 95
  • 1
    You can flatten out your promise chain by returning the promise, see here: http://www.datchley.name/promise-patterns-anti-patterns/ – Evan Trimboli Feb 07 '17 at 23:48

1 Answers1

0

Yes, you can and should flatten your chain. To do that you'll need to return the inner promises from the then callbacks, which you will need anyway to make the single catch in the end work.

return validateUser()
.then(getUserInformation)
.then(userInformation =>
  Promise.all([
    getUserDebitAccounts(userInformation), 
    getUserCreditAccounts(userInformation)
  ])
).then(([drAcc, crAcc]) => {
  // do something
  return …;
})
.catch(error => {
  console.error(error);
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • seems like we can combine first two calls in `.all` as they are independent. So just wanna check if `Promise.all([validateUser(), getUserInformation()]).then(([, userInformation]) => {...}).then(..).catch(..)` will be right way to put calls too. – αƞjiβ Feb 08 '17 at 05:05
  • Yes, you can do that *if* they are independent. However it looks like you would want to validate a user *before* getting any information about them. (Though if that was the case, I'd recommend not relying on side effects but explicitly passing a `validatedUser` object between them) – Bergi Feb 08 '17 at 05:38
  • Do we need to add return on first two `then` calls - – αƞjiβ Feb 08 '17 at 14:50
  • @αƞjiβ Yes, you should [always `return`](http://stackoverflow.com/a/25756564/1048572). In the arrow function shorthand, it's implicit. – Bergi Feb 08 '17 at 17:11