I don't understand the behavior of this javascript program. My intent was to sequentially fetch three numbered resources, but it seems like "i" has been captured in a closure and only its final value is used.
function fetch(x) {
console.log('fetching resource ' + x);
}
var prom = Promise.resolve();
for(var i=1; i<=3; i++) {
prom = prom.then(() => { fetch(i);} );
}
//prints
//fetching resource 4
//fetching resource 4
//fetching resource 4
I don't know enough about js to solve this -- how might I modify this program to produce 1, 2, and 3? Do I need to use resolve() somewhere?
UPDATE: it has been pointed out that this question is duplicative of JavaScript closure inside loops – simple practical example, which is technically true, but nonetheless I think this question has merit because of its new application in the world of Promises. Technically, the aforementioned question does correctly answer the question posed here, because the Promise element in this question turns out to be a red herring not relevant to the answer. But the recognition of the Promise as being irrelevant is an insight gained by reading this question and not the aforementioned duplicate.