I'm trying to understand thunks. I'm going through Kyle Simpson's Rethinking Async JS course on Lynda.
I have this code:
function makeThunk(fn) {
var args = [].slice.call(arguments, 1);
return function(cb) {
args.push(cb);
fn.apply(null, args);
}
}
function addAsync(x,y, cb) {
setTimeout(function() {
cb(x+y);
}, 1000);
}
var thunk = makeThunk(addAsync, 10,15);
Now, when I execute the following:
thunk(function(sum) {
console.log(sum * sum);
})
thunk(function(sum) {
console.log(sum);
})
The result is 625 printed twice.
However, when I execute
thunk(function(sum) {
console.log(sum);
})
thunk(function(sum) {
console.log(sum * sum);
})
The result is 25 executed twice.
My expectation in the first case is 625 printed then 25. And in the second case 25 is printed then 625.
Why is my expectation incorrect?