我有几个带有不同数量参数的异步函数,每个参数中的最后一个都是回调。我希望依次称呼这些。例如。
function getData(url, callback){
}
function parseData(data, callback){
}
通过使用此:
Function.prototype.then = function(f){
var ff = this;
return function(){ ff.apply(null, [].slice.call(arguments).concat(f)) }
}
可以像这样调用这些函数,并将输出打印到console.log。
getData.then(parseData.then(console.log.bind(console)))('/mydata.json');
我一直在尝试使用此语法,但无法正确获取Then函数。有任何想法吗?
getData.then(parseData).then(console.log.bind(console))('/mydata.json');
罗伯特·罗斯曼(Robert Rossmann)是对的。但我愿意纯粹出于学术目的回答。
让我们将代码简化为:
Function.prototype.then = function (callback){
var inner = this;
return function (arg) { return inner(arg, callback); }
}
和:
function getData(url, callback) {
...
}
让我们分析每个函数的类型:
getData
是(string, function(argument, ...)) → null
。function(argument, function).then
是(function(argument, ...)) → function(argument)
。这是问题的核心。当您这样做时:
getData.then(function (argument) {})
它实际上返回类型为的函数function(argument)
。这就是为什么.then
不能调用它的原因,因为.then
期望被调用到function(argument, function)
类型上。
您要做的是包装回调函数。(在的情况下getData.then(parseData).then(f)
,你想换parseData
用f
,而不是结果getData.then(parseData)
。
这是我的解决方案:
Function.prototype.setCallback = function (c) { this.callback = c; }
Function.prototype.getCallback = function () { return this.callback; }
Function.prototype.then = function (f) {
var ff = this;
var outer = function () {
var callback = outer.getCallback();
return ff.apply(null, [].slice.call(arguments).concat(callback));
};
if (this.getCallback() === undefined) {
outer.setCallback(f);
} else {
outer.setCallback(ff.getCallback().then(f));
}
return outer;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句