Last active
March 21, 2024 07:07
-
-
Save dfkaye/d2906c28a519a61014d13489944da608 to your computer and use it in GitHub Desktop.
fake fetch iife closure test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 20 March 2024 | |
// fake fetch iife closure test | |
// Twitter posed a question at | |
// https://twitter.com/jcubic/status/1770519375944040682 | |
// So I answered. I've since been blocked. *shrug* | |
// Here's what I get with a fake fetch, F: | |
// An async function returns a resolved promise. | |
async function F(url) { return url; } | |
// The log function in the promise.then() clause will report the current | |
// value of `id`, not its value when the fake request is made. | |
for (var id of ['a', 'b', 'c']) { | |
F('/path/' + id).then(value => console.log(value, id)); | |
} | |
// In this case, all logs of `id` resolve to `c`, the final value at the | |
// end of the for loop. | |
/* | |
/path/a c | |
/path/b c | |
/path/c c | |
*/ | |
// An IIFE for each loop step fixes that by capturing the value at | |
// request time in the function's parameter list: | |
for (var id of ['a', 'b', 'c']) { | |
(function (id) { | |
F('/path/' + id) | |
.then(value => console.log(value, id)); | |
})(id); | |
} | |
/* | |
/path/a a | |
/path/b b | |
/path/c c | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment