简体   繁体   中英

Using thunks: Why isn't my code printing sequentially?

I'm trying to understand thunks. I'm going through Kyle Simpson's Rethinking Async JS course on Lynda.

I have this code:

function makeThunk(fn) {
    var args = [].slice.call(arguments, 1);
    return function(cb) {
        args.push(cb);
        fn.apply(null, args);
    }
}

function addAsync(x,y, cb) {
    setTimeout(function() {
        cb(x+y);
    }, 1000);
}


var thunk = makeThunk(addAsync, 10,15);

Now, when I execute the following:

thunk(function(sum) {
    console.log(sum * sum);
})

thunk(function(sum) {
    console.log(sum);
})

The result is 625 printed twice.

However, when I execute

thunk(function(sum) {
    console.log(sum);
})
thunk(function(sum) {
    console.log(sum * sum);
})

The result is 25 executed twice.

My expectation in the first case is 625 printed then 25. And in the second case 25 is printed then 625.

Why is my expectation incorrect?

var thunk = makeThunk(addAsync, 10,15);

After that the closured args array is:

[10, 15]

Now if you call thunk :

thunk(function one(sum) {
console.log(sum * sum);
})

The internal args is:

[10, 15, one]

And the function is executed the first time. Then you call:

thunk(function two(sum) {
  console.log(sum);
})

So args will look like this:

[10, 15, one, two]

So addAsync is called like:

addAsync(10, 15, one, two)

So cb is one again, therefore the first function is executed twice.


To resolve this, you may want to change the modification through push into an nonmutating concat:

return function(cb) {
    fn.apply(null, args.concat(cb));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM