I'm following along with the Kyle Simpson Rethinking Asynchronous JavaScript video course and am confused about how his thunk pattern is using closures. The code is like this:
function ajax(url, cb) {
$.ajax({ url: `text/${url}`, type: 'GET', dataType: 'json' })
.done(data => {
cb(data)
})
}
function getFile(file) {
var text, fn;
ajax(file,function(response){
if (fn) {
fn(response)
} else {
text = response
}
})
return function th(cb) {
if (text) {
cb(text)
} else {
fn = cb
}
}
}
var th1 = getFile('1')
var th2 = getFile('2')
var th3 = getFile('3')
th1(function ready(text){
console.log(text)
th2(function ready(text){
console.log(text)
th3(function ready(text){
console.log(text)
th2(function (text) {
console.log(text)
})
})
})
})
I added the extra call to th2 in the final nested portion. I expected this use of closures to return the value originally printed from th2, stored in the closure variable text in the getFile function, ie not make another network call. Though that is not what happens: execution stops after printing the text in the t3 callback.