我正在关注Kyle Simpson Rethinking Asynchronous JavaScript视频课程,并且对他的 thunk 模式如何使用闭包感到困惑。代码是这样的:
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)
})
})
})
})
th2
我在最后的嵌套部分添加了额外的调用。我希望这种闭包的使用能够返回最初打印的值th2
,存储在函数的闭包变量text
中getFile
,即不会进行另一个网络调用。虽然这不是发生的事情:在t3
回调中打印文本后执行停止。