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;
}
I believe that continuations are a special case of callbacks. A function may callback any number of functions, any number of times. For example:
var array = [1, 2, 3];
forEach(array, function (element, array, index) {
array[index] = 2 * element;
});
console.log(array);
function forEach(array, callback) {
var length = array.length;
for (var i = 0; i < length; i++)
callback(array[i], array, i);
}