2 回答

TA貢獻1818條經驗 獲得超3個贊
id 是索引,而不是實際值。您需要做的就是附加 userIds[id],而不是附加 id
const userIds = [
// Squall
'226618912320520192',
// Tofu
'249855890381996032',
// Alex
'343201768668266496',
// Jeremy
'754681236236140666',
// Maddo
'711211838305599538',
// Arden
'375573674306306050',
// Neo
'718874307316678698',
// Mytho
'480092510505402380',
// Yuun
'630427600220717067'
];
const fetchData = async() => {
let users = [];
for (const id in userIds) {
const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=' + userIds[id]);
const user = await response.json();
users.push(user);
}
return users;
}
fetchData().then(ele => console.log(ele)).catch(e => console.log(e.message))
與當前問題無關,在 for 循環中等待并不是一個好的做法。在 for 循環中等待,等待每個調用完成,然后再執行下一個調用。使用 Promise.all 將同時進行所有調用。下面是 Promise.all 的片段。
const fetchData = async() => {
let users = [];
for (const id in userIds) {
users.push(fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=' + userIds[id]));
}
const results = await Promise.all(users);
return Promise.all(results.map(result => result.json()));
}

TA貢獻1772條經驗 獲得超6個贊
如果你只是這樣做
for (const id in userIds) {
console.log(id);
}
你就會看到問題所在。在此循環中,id是鍵,而不是值。你可能會得到404s 作為回報。
使用for... of循環代替for... in.
添加回答
舉報