![](/img/trans.png)
[英]× Unhandled Rejection (SyntaxError): Unexpected end of JSON input
[英]Getting “Unhandled Rejection (SyntaxError): Unexpected end of JSON input”
這是我的代碼:
const userIds: string[] = [
// Squall
'226618912320520192',
// Tofu
'249855890381996032',
// Alex
'343201768668266496',
// Jeremy
'754681236236140666',
// Maddo
'711211838305599538',
// Arden
'375573674306306050',
// Neo
'718874307316678698',
// Mytho
'480092510505402380',
// Yuun
'630427600220717067'
];
const fetchData = async() => {
let users: User[] = [];
for (const id in userIds) {
const response = await fetch('https://api.codetabs.com/v1/proxy/?quest=http://hamsterland.herokuapp.com/api/users?id=' + id);
const user: User = await response.json();
users.push(user);
}
}
我收到錯誤Unhandled Rejection (SyntaxError): Unexpected end of JSON input
。
如果我分別使用每個 Id 的 API,都返回有效的 JSON。 但是,它在for
循環中不起作用。
如果你只是這樣做
for (const id in userIds) {
console.log(id);
}
你會看到問題。 在這個循環中, id
是keys ,而不是values 。 您可能會得到404
作為回報。
使用for... of
循環而不是for... in
。
id 是索引,而不是實際值。 您需要做的就是而不是附加 id,append userIds[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 循環中的 await 不是一個好習慣。 在 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()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.