Tylik Stec Tylik Stec - 1 year ago 91
Javascript Question

how to rewrite callback hell into promise?

my callback hell route works fine...

var myCallbackHell = router.route('/');
myCallbackHell.get(function(req, res, next) {
bookModel.find({title: "Animal Farm"}).then(function(book) {
movieModel.find({title: "Intouchables"}).then(function(movie) {
gameModel.find({title: "The Last of Us"}).then(function(game) {
res.render('index', {book_found: book, movie_found: movie, game_found: game});

however I would like to use promise. Any help, hint?

Answer Source

You can use Promise.all and write the same, like this

var promises = [
  bookModel.find({title: "Animal Farm"}),
  movieModel.find({title: "Intouchables"}),
  gameModel.find({title: "The Last of Us"})

Promise.all(promises).then(function(values) {
  res.render('index', {book_found: values[0], movie_found: values[1], game_found: values[2]});
}).catch(function(err) {
  // deal with err
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download