It has been a week since the last post , i was busy in my academics . Here is our new tutorial on Sails JS . This time its a very useful topic. We’ll deal with removing
Callback Hell (also called
What's actually Pyramid of Doom in JS ?
Look at the picture below . This is a popular example from MDN .
Here we can see that we are doing the operations on success of related functions which makes code weird. How can remove this problem ?. Here we have a solution . We can use promises by which can remove Callback Hell .
Consider an application where we have
- Student Model with Name , Classroom id , student id
- Classroom Model with Name , Classroom id
Here if we want to
retrieve the list of all students who is in the same class of a given student and the api should return classroom details also
Callback / Normal Approach
- Get the details of given student
- On success of the above query , get the details of classroom
- On success of the above query , get the details of all students who are in that classroom
This can be achieved by following code segment.
We can see another approach here .
We’ll be using promises which is available in Sails by default.
Promises use the Q library, so anything you do after the first then call (or spread, or fail), will be a complete
Q promise object. Remember, you must end the query somehow (by calling then or one of the other functions) in order to complete the database request.
Here we are not waiting for Classroom data to be fetched , both student details and classroom details are fetched at the same time .
Yaay!!! It works … We have created an API with promises here . We’ll see advanced experiments with Sails in coming tutorials.. See you there bye