Skip to content

Instantly share code, notes, and snippets.

@joepie91
Created May 3, 2015 13:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joepie91/977c966cb0d6c15690b0 to your computer and use it in GitHub Desktop.
Save joepie91/977c966cb0d6c15690b0 to your computer and use it in GitHub Desktop.
Callbacks in Javascript
function getUser(userID, callback) {
/* This is a hypothetical function. Normally we'd talk to a database or so, but this is to illustrate the concept... */
var someUser = {name: "Joe Bloggs", age: 42};
callback(someUser); /* Here we call the callback from the second function argument, with our fake user */
}
/* Code: */
getUser(42, function(user){
/* Now `user` contains {name: "Joe Bloggs", age: 42} */
});
/* We could also write this as: */
function whenDone(user) {
/* Now `user` contains {name: "Joe Bloggs", age: 42} */
}
getUser(42, whenDone);
@steltenpower
Copy link

wouldn't it be easier to understand when age and userID were not the same number?

@diogocapela
Copy link

Shouldn't it be like this instead?

function getUser(someUser, callback) {

}

@tombusby
Copy link

tombusby commented Aug 18, 2018

@diogocapela No because he's simulating a DB call.

It would normally be:

var someUser = db.getUserById(userID);

But instead he's just creating an object and pretending that's what he looked up with the userID.

It would probably be clearer if he made use of that getUser function he created though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment