我正试图在makeThunk
函数中编写代码,但在这里我无法理解如何在makethunk
函数中传递cb
的值。
我想在用回调调用thunk后记录总和值!
我的代码看起来像这样:
"use strict";
function addAsync(x,y,cb) {
setTimeout(function () {
cb(x+y);
},1000);
};`enter code here`
var thunk = makeThunk(addAsync,10,15);
function makeThunk(){`enter code here`};
thunk(function(sum){
console.log(sum);
});
也许,您正在寻找以下内容:
"use strict";
function addAsync(x,y,cb) {
setTimeout(function () {
cb(x+y);
},1000);
};
var thunk = makeThunk(10,15);
function makeThunk(num1,num2){
return function(cb) {
addAsync(num1,num2,cb);
}
};
thunk(function(sum) {
console.log(sum);
});
您可以使用传递x
、y
和cb
的Function.prototype.bind()
作为参数
"use strict";
function addAsync(x, y, cb) {
setTimeout(function() {
cb(x + y);
}, 1000);
}
function makeThunk(fn) {
fn()
}
var thunk = makeThunk(addAsync.bind(null, 10, 15, function(sum) {
console.log(sum)
}))
function makeThunk(...args){
return function(cb){
args.push(cb)
addAsync(...args)
}
}
只需使用es6 中新增的rest/spread运算符语法