2

If I have a view in my (mvc project) contains data from many tables in the database, what is the best way to fetch them without getting into the nested tree of doom

Model1.findAll().then(model1Data => {
  Model2.findAll().then(model2Data => {
    Model3.findAll().then(model3Data => {
      Modeln.findAll().then(modelnData => {
        res.render('view', {
          model1Data: model1Data,
          model2Data: model2Data,
          model3Data: model3Data,
          modelnData: modelnData
        });
      })
    })
  })
})

Note: the above query has no where clauses, joins, or any other conditions

Ebrahim Mansour
  • 363
  • 1
  • 4
  • 13
  • If you have Sequelize Associations beetwin your Models, you can use Include to extract all the data [link](http://docs.sequelizejs.com/manual/tutorial/querying.html#relations-associations) If not, you can consider have a separated folder that contains all your models logic and call each required function, also, this should be helpful if you need show some info in other views (not all data) – masmerino Dec 19 '18 at 14:29
  • also async / await syntax should work on that case – masmerino Dec 19 '18 at 14:34
  • Already I have a separated folder for the models logic, but the same problem will happens when I call each one because the returned value will be promise and I have to use nesting to can use them at all – Ebrahim Mansour Dec 19 '18 at 14:43
  • @vivek-doshi answer should work! – masmerino Dec 19 '18 at 14:55

1 Answers1

3

Here you can use 2 ways either Promise.all() or async/await :

Promise.all() :

const promises = [
    Model1.findAll(),
    Model2.findAll(),
    Model3.findAll(),
    Modeln.findAll()
]

Promise.all(promises).then((data) => {
    res.render('view', data );
});

Async/await :

let model1Data = await Model1.findAll();
let model2Data = await Model2.findAll();
let model3Data = await Model3.findAll();
let modelnData = await Modeln.findAll();
res.render('view', {
    model1Data: model1Data,
    model2Data: model2Data,
    model3Data: model3Data,
    modelnData: modelnData
});

NOTE :

I would suggest to use Promise.all() if the queries are not dependent on each other , as it will start execution and don't wait for the first one to complete as it does in async/await.

For More Deatil : DO READ

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • The first way works well with my, but the second one gives me the following error: SyntaxError: await is only valid in async function – Ebrahim Mansour Dec 19 '18 at 15:01
  • 1
    Yes you have to put async before function your_func_name(), please. See any async await function you will get idea , – Vivek Doshi Dec 19 '18 at 15:54