javascript async.js 库中的咖喱示例
javascript curry example in async.js library
我正在阅读 async.js 库的源代码,并在其中找到了一个名为 'only_once' 的函数,然后我尝试了一些示例来弄清楚它是如何工作的,但我不能'不要弄清楚我的例子有什么问题,因为它们根本没有按照应有的方式行事。这是我的代码:
function only_once(fn) {
var called = false;
return function () {
if (called) throw new Error('Callback was already called.');
called = true;
fn.apply(this, arguments);
};
}
// my example code
var add = function (a, b) { return a + b; };
var add_once = only_once(add);
var a = add_once(1, 3);
console.log(a); // this prints undefined not 4, what the hell ?????
only_once()
当前未对 fn
的结果执行任何操作——在本例中为 add
。
它应该提供来自 fn
的 return
值作为它自己的值:
return fn.apply(this, arguments);
// vs.
fn.apply(this, arguments);
在上下文中:
// ...
return function () {
if (called) throw new Error('Callback was already called.');
called = true;
return fn.apply(this, arguments);
};
// ...
在 async.js
中,未使用 return
值,因此不必提供。
该库专为异步函数而设计,它接受回调函数作为稍后调用并传递结果的参数。
only_once
只是防止它们被多次调用:
function asyncFunc(callback) {
setTimeout(callback, 100); // callback invoked
setTimeout(callback, 200); // Uncaught Error: Callback was already called.
}
asyncFunc(only_once(function (value) {
console.log('callback invoked');
}));
我正在阅读 async.js 库的源代码,并在其中找到了一个名为 'only_once' 的函数,然后我尝试了一些示例来弄清楚它是如何工作的,但我不能'不要弄清楚我的例子有什么问题,因为它们根本没有按照应有的方式行事。这是我的代码:
function only_once(fn) {
var called = false;
return function () {
if (called) throw new Error('Callback was already called.');
called = true;
fn.apply(this, arguments);
};
}
// my example code
var add = function (a, b) { return a + b; };
var add_once = only_once(add);
var a = add_once(1, 3);
console.log(a); // this prints undefined not 4, what the hell ?????
only_once()
当前未对 fn
的结果执行任何操作——在本例中为 add
。
它应该提供来自 fn
的 return
值作为它自己的值:
return fn.apply(this, arguments);
// vs.
fn.apply(this, arguments);
在上下文中:
// ...
return function () {
if (called) throw new Error('Callback was already called.');
called = true;
return fn.apply(this, arguments);
};
// ...
在 async.js
中,未使用 return
值,因此不必提供。
该库专为异步函数而设计,它接受回调函数作为稍后调用并传递结果的参数。
only_once
只是防止它们被多次调用:
function asyncFunc(callback) {
setTimeout(callback, 100); // callback invoked
setTimeout(callback, 200); // Uncaught Error: Callback was already called.
}
asyncFunc(only_once(function (value) {
console.log('callback invoked');
}));