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

4
  • If you have Sequelize Associations beetwin your Models, you can use Include to extract all the data link 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) Commented Dec 19, 2018 at 14:29
  • also async / await syntax should work on that case Commented Dec 19, 2018 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 Commented Dec 19, 2018 at 14:43
  • @vivek-doshi answer should work! Commented Dec 19, 2018 at 14:55

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

The first way works well with my, but the second one gives me the following error: SyntaxError: await is only valid in async function
Yes you have to put async before function your_func_name(), please. See any async await function you will get idea ,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.