søndag 22. desember 2013

Callback Mountain - straight up asyncronous

Yeah, the title's a bit quirky, but .. bare with me.

The word "callback" is everywhere in documentation of JavaScript frameworks and libraries. But what is it?

The gist of it


Here it is: Pass a function into another function as a parameter. It's like when you pass a variable. You pass a value and give it an internal name, and can the pick up the content when you need by referring to the name. So this is what you do with vars:
b = "Print this!";
function a(b){
console.log("b is: " + b);
};

Call a("to be"); and it prints "b is: to be".

With callbacks it's the same:
function printStuff(callback){
console.log("Callback prints: " +
callback("it!"))
};

When we call printstuff(a); it prints: "Callback prints: b is: it!"

What happens is that we pass in a("it!"), which is set to just dump the text "b is: " and whatever b is. Which in this case is "it!".

The use of it


Wikipedia says: "A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time."

In an asynchronous language like JavaScript this is usefull since there's a lot of waiting for the opportune moment. There are ajax calls you never know when will be ready - if ever. So you can say: Get this, when you got it, do that.

Or for events: listen for that, when it happens do that thing you know.

The core of it


How is this possible? Functions in JavaScript are objects created with the Function constructor. The object contains a string. This string is the code of the function. Or something.

This means you can pass code to a function, just as you pass variables or other objects, because all you're really passing is an object.

More sources:

 

Etiketter:

0 Kommentarer:

Legg inn en kommentar

Abonner på Legg inn kommentarer [Atom]

<< Startsiden