为嵌套的Promise调用编写mocha测试

时间:2017-02-07 23:41:25

标签: javascript promise

我有嵌套的promise调用结构如下:

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

首先有一种简化这些嵌套调用的方法吗?如您所见,它们是依赖的结构。所以这是我提出的最合乎逻辑的方式。

其次,我可以在结尾处使用catch来捕获所有上述呼叫中的所有拒绝。我是否必须为每次通话添加单独的catch

第三,我想写一个mocha测试,对于这些方法,我必须做什么级别的Promise模拟,一些大纲会有所帮助。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

是的,you can and should flatten your chain。要做到这一点,您需要then回调中的return the inner promises,无论如何您都需要这些回调才能使单catch完成工作。

return validateUser()
.then(getUserInformation)
.then(userInformation =>
  Promise.all([
    getUserDebitAccounts(userInformation), 
    getUserCreditAccounts(userInformation)
  ])
).then(([drAcc, crAcc]) => {
  // do something
  return …;
})
.catch(error => {
  console.error(error);
});
相关问题