Monday, 31 July 2017

javascript - How to pass data by value into a deferred then handler?

I would like to know how to pass data by value, rather than by reference, into a then handler on a jQuery Deferred object.



I have the following example code to illustrate my question:




var value;
var deferred = new $.Deferred();
var data = ["A", "B", "C", "D"];

// add a separate call to the chain for each piece of data
for (var i = 0; i < data.length; i++) {
value = data[i];
deferred.then(function(response) {
console.log(response+':'+value);

});
}

deferred.resolve("test");


The result I want to get:



test:A
test:B

test:C
test:D


The result I actually get:



test:D
test:D
test:D
test:D



It seems the value of value is evaluated at the time the then handler is executed, whereas I want it to be evaluated at the time the then handler is queued.



I have a JSfiddle, hope someone can help?

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...