0

I'm new in js. In my project I'm using mysql and node js. Somewhere in controller I need to get some data from differnet models. In php it looks like

function some() {
    $user = $user->getOne($id); 
    $photos = $photos->getOne($user->id);
    $posts  = $post($user->id, $photo->uid)
}

and I have all this variables in one scope in node js result of model is async, so it's look like nestings callbacks. Short example

UserModel.findbyid(result.user_id, function (err, user_data) {
  PhotoModel.GetVoteCount(user_data.id, result.id, function (res_count) {
    PhotoModel.getWinners(function (err, winners_ar) {
      PhotoModel.getweekusers(1, function (result_week) {
        response.render('one.twig', {
          view_user: request.user,
          image: result,
          p_user: user_data,
          count: res_count,
          winners: winners_ar,
          week_users: result_week['photos']
        });
      });
    })
  });
});
so I have nested callbacks, I feel it's not right way to code, can you explain best practices?
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • `write` or `right`? – Rajesh Nov 22 '16 at 13:23
  • This is the right way of coding in JavaScript :) You can check this blog post for example http://www.joshwright.com/tips/javascript-christmas-trees-promises-and-event-emitters, and if you Google `Christmas Trees of Doom JavaScript`, you'll find some good article that will explain why this is, and how to get use to it :) – David Gatti Nov 22 '16 at 13:27

3 Answers3

0

You can take a look at async module

This simplifies what you call "callback hell" through some functions that helps create flows in async code.

Specifically to your case - async.waterfall will do the trick

gibson
  • 1,066
  • 2
  • 10
  • 22
0

You have two options :

  1. Use async module (async)
  2. Use a library which returns promises (like promise-mysql).
Sachin
  • 3,350
  • 2
  • 17
  • 29
0

Use promises,or libraries that will help you use promises.

shadrack Mwangi
  • 785
  • 6
  • 14