I am trying to work out how to implement an asynchronous callback in node given that I don’t know what the arguments could be.
I’ll state the sync version of what I’m trying to do so as to make this clearer.
function isAuthorized(userID){
// check for user Permissions here
return isAuthorized;
}
Using this any function can call it and, from the value it returns, determine if the user is authorized. However, the function that I use to get the userID (and check for permissions) are both asyncronous functions and require callbacks. However I have no idea how to get this implemented when I don’t know the arguments needed in the callback.
The function that calls this could want to send an number of arguments to the callback (normally it’d just wait for a return in sync) and that’s what’s confusing me.
function isAuthorized(socket, callback, args){
socket.get('userID', function (err, userID) {
//check userID for permission
callback(args);
});
}
I realize I could convert the arguments into an array and send that array, but I wanted to know if there is a more general way to do this that doesn’t force me to make all my callbacks convert from an array of arguments.
Hope you can help,
Pluckerpluck
You can always create a function to pull those arguments into an array for you, and then reuse it in each of your async functions:
This will then enable you to do things like this:
There’s a fiddle here to play with.