Rohit Bajaj
asked on
Better way of using callback in javascript
Hi,
Here is the code which i am using ... this includes a callback... although code seems to be working fine.. Need help from experts on its design a better way to write the same or any flaws in it :
Thanks
Here is the code which i am using ... this includes a callback... although code seems to be working fine.. Need help from experts on its design a better way to write the same or any flaws in it :
clock.groups.list(userId, callback);
clock.roster.listContacts(userId, callback);
var callback = function(errorThrown, data, name) {
if(errorThrown === null) {
if(name === 'groups.list') {
mygroupList = data;
}
else if (name === 'roster.listContacts') {
data.forEach(function(elem){mybuddyList.push(elem)});
}
}
}
exports.groups = {};
exports.groups.list = function(userId, callback) {
callMethod('groupList', userId, callback);
}
exports.roster = {};
exports.roster.listContacts = function(userId, callback) {
callMethod('listContacts', userId, callback);
}
callMethod = function(name, userId, callback) {
$.ajax({
url : endpoint,
type: 'POST',
contentType: 'application/json',
headers: {
'X-user-id': userId,
},
dataType: 'json',
success: function(data, textStatus, jqXHR){
callback(null, data, name);
},
error: function(jqXHR, textStatus, errorThrown) {
callback(errorThrown, null, name);
}
});
}
Thanks
Why would you want to do that if it's working... Not sure I understand? Is it an assignment?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
no its not an assignment.. but its always good to look for alternatives and improve code quality... may be my code has some design flaws...for which i need advice from experts...
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
what is clock.groups.list and clock.roster.listContacts?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.