I've been browsing all over the web in search of enlightenment about continuations, and it's mind boggling how the simplest of explanations can so utterly confound a JavaScript programmer like myself. This is especially true when most articles explain continuations with code in Scheme or use monads.
Now that I finally think I've understood the essence of continuations I wanted to know whether what I do know is actually the truth. If what I think is true is not actually true, then it's ignorance and not enlightenment.
So, here's what I know:
In almost all languages functions explicitly return values (and control) to their caller. For example:
var sum = add(2, 3);
console.log(sum);
function add(x, y) {
return x + y;
}
Now in a language with first class functions we may pass the control and return value to a callback instead of explicitly returning to the caller:
add(2, 3, function (sum) {
console.log(sum);
});
function add(x, y, cont) {
cont(x + y);
}
Thus instead of returning a value from a function we are continuing with another function. Therefore this function is called a continuation of the first.
So what's the difference between a continuation and a callback?