Node.js Callback manipulation check

- 1 answer

Ad

I am writing a scheduling program that returns JSON data about courses. I just started Node.js a week ago so I'm not sure if I'm thinking right. I am trying to find a better way to write this code and avoid callback hell. I have already written the getJSON method.

/*getJSON(course-name, callback(JSONretrieved)): gets JSON info about name and
takes in a callback to manipulate retrieved JSON data*/

Now I want to get multiple course-name from a course array and check for time conflicts between them. I will then add all viable combinations to an answer array. My current idea is:

/*courseArray: array of classes to be compared
answers: array of all nonconflicting classes*/
var courseArray = ['MATH-123','CHEM-123']
var answers=[]
getJSON(courseArray[0],function(class1data){
    getJSON(courseArray[1],function(class2data){
         if(noConflict) answers.push( merge(class1data,class2data))
     })
    )
  })
);

Finally, to access the answer array we wrap the entire code from above:

function getAnswers(cb){
    /*courseArray: array of classes to be compared
answers: array of all nonconflicting classes*/
var courseArray = ['MATH-123','CHEM-123']
var answers=[]
getJSON(courseArray[0],function(class1data){
    getJSON(courseArray[1],function(class2data){
         /check for time conflicts between class1data and class2 data
         if(noConflict(class1data,class2data)) answers.push( merge(class1data,class2data))
     })
    )
  })
);
cb(answers)
}

and we call the function

getAnswers(function(ans){
  //do processing of answers
  console.log(ans)
})

My main question is if there is any way to make this code shorter, more readable, or less callback hecky.

Ad

Answer

Ad

You can use a promise library to make things easier for yourself. The way you're doing it can quickly get out of hand if the user selects more than a handful of courses to compare.

With something like async, you can make parallel calls to getJSON and your conflict code will run inside a single callback once all of the getJSON calls have returned. Your code will be much more readable and maintainable for large arrays of courses.

Ad
source: stackoverflow.com
Ad