提取API的json正在打印未定义?

时间:2019-03-23 20:18:25

标签: javascript fetch

尝试从JS中的API获取并且返回的JSON返回未定义?是的,它是有效的JSON,尽管console.loging数据显示未定义?

function getVideos(playlistId) {
    console.log(
        getJsonResponse(composeArguments(API_RESOURCE, API_KEY, playlistId))
    );
}


function composeArguments(apiResource, apiKey, playlistId, maxResults = 50) {
    return (
        apiResource +
        "?key=" +
        apiKey +
        "&part=snippet&playlistId=" +
        playlistId +
        "&maxResults=" +
        maxResults);
}

function getJsonResponse(url) {
    fetch(url).then((response) => {
        if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code: ' + response.status);
            return;
        }

        response.json().then((data) => {
            return data;
        });
    }).catch(function (err) {
        console.log('Fetch Error :-S', err);
    });

}




getVideos(PLAYLIST_ID);

2 个答案:

答案 0 :(得分:1)

fetch的 then 下的函数实际上没有返回值。因此console.log(getJsonResponse...日志未定义。 getJsonResponse必须返回某些内容(承诺或值)。

仅使用response.json().then(data => { return data; })代替return response.json();

答案 1 :(得分:0)

尝试在response.json()之前追加返回。休息似乎很好。调用的函数应该返回一些值。

`function getJsonResponse(url) {
   return fetch(url).then((response) => {
     if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' + response.status);
        return 'Looks like there was a problem.';
    }

    return response.json().then((data) => {
        return data;
    });
}).catch(function (err) {
    console.log('Fetch Error :-S', err);
});

}`