Paran0a
Paran0a

Reputation: 3457

Chain promises when rendering template

Function that fetches data.

Get a connection and fetch some data. Omitted some code.

function executeSQL(sql, bindParams , options) {
  return new Promise(function(resolve, reject) {
    ...
    resolve(result);
  });
}

Controller that uses that function

exports.index = function(req, res){

    database.executeSQL('SELECT 1 FROM DUAL', [] , {})

    .then(function(result) {
      res.render('index' , { TITLE : 'Lorem Ipsum Blog' });
    })

    .catch(function(err) {
      next(err);
    });
};

My index controller is used in my index route.

I'll need to call my executeSQL function at least twice. Only after both of them are done do I want to call res.render and send in my data that I fetched.

How do I chain them? Do I even need to chain them? Can I just execute them asynchronically and once they're both done then I call res.render.

Upvotes: 0

Views: 72

Answers (1)

Rayon
Rayon

Reputation: 36599

Use Promise.all, The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved.

function executeSQL(sql, bindParams, options) {
  return new Promise(function(resolve, reject) {
    resolve(result);
  });
}
exports.index = function(req, res) {
  var pro1 = database.executeSQL('SELECT 1 FROM DUAL', [], {});
  var pro2 = database.executeSQL('SELECT 1 FROM DUAL', [], {});
  Promise.all([pro1, pro2]).then(function(result) {
    console.log(result); //result will be an array
    res.render('index', {
      TITLE: 'Lorem Ipsum Blog'
    });
  }).catch(function(err) {
    next(err);
  });
};

Upvotes: 1

Related Questions