此代码按预期工作:
for (let i = 0; i < 2; i++) {
try {
let id = 'id ' + i;
const request = fetch('https://httpbin.org/get?a=' + i).then(r => {
if (r.ok) {
r.json().then(o => {
console.log(id);
console.log('response', o.args.a);
});
}
});
} catch {}
}
为什么
id
总是等于1
?
for (let i = 0; i < 2; i++) {
try {
var id = 'id ' + i;
} catch {}
try {
const request = fetch('https://httpbin.org/get?a=' + i).then(r => {
if (r.ok) {
r.json().then(o => {
console.log(id);
console.log('response', o.args.a);
});
}
});
} catch {}
}
for (let i = 0; i < 2; i++) {
try {
var id = 'id ' + i;
const request = fetch('https://httpbin.org/get?a=' + i).then(r => {
if (r.ok) {
r.json().then(o => {
console.log(id);
console.log('response', o.args.a);
});
}
});
} catch {}
}