猿问

获取“未处理的拒绝(语法错误):JSON 输入意外结束”

这是我的代码:


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。


撒科打诨
浏览 104回答 2
2回答

泛舟湖上清波郎朗

id 是索引,而不是实际值。您需要做的就是附加 userIds[id],而不是附加 idconst 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()));}

梦里花落0921

如果你只是这样做for (const id in userIds) {    console.log(id);}你就会看到问题所在。在此循环中,id是键,而不是值。你可能会得到404s 作为回报。使用for... of循环代替for... in.
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答