亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

獲取“未處理的拒絕(語法錯誤):JSON 輸入意外結束”

獲取“未處理的拒絕(語法錯誤):JSON 輸入意外結束”

撒科打諢 2023-10-14 18:35:47
這是我的代碼: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,則所有 API 都會返回有效的 JSON。但是,它在循環中不起作用for。
查看完整描述

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()));

}


查看完整回答
反對 回復 2023-10-14
?
夢里花落0921

TA貢獻1772條經驗 獲得超6個贊

如果你只是這樣做


for (const id in userIds) {

    console.log(id);

}

你就會看到問題所在。在此循環中,id是鍵,而不是值。你可能會得到404s 作為回報。


使用for... of循環代替for... in.


查看完整回答
反對 回復 2023-10-14
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號