【发布时间】:2017-08-10 01:46:56
【问题描述】:
我正在关注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 打印的值,存储在getFile 函数中的闭包变量text 中,即不进行另一个网络调用。虽然这不是发生的情况:在t3 回调中打印文本后执行停止。
为什么这个闭包不返回它已经检索到的值?
【问题讨论】:
-
那些笨蛋看起来像是穷人的承诺。我想知道他为什么放弃他已经拥有的 jQuery 承诺。
-
@Bergi 他没有使用 jquery。我把它扔在那里,这样我就可以快速验证网络面板中发生了什么。他最初有一个使用超时的
fake_ajax方法。 -
@bergi 他使用这些 thunk 作为谈论承诺的一部分。
标签: javascript callback closures thunk