最近,我一直在使用YouTube Javascript API,但我遇到了问题(一如既往!)。

我需要一个函数来返回有关视频的信息数组:

 [0: Title, 1: Description, 2: Publish Date, 3: Thumbnail URL]

该函数获取视频的ID,然后使用该ID进行video.list。这是该函数:
function getVidInfo(VidId){
    var vidRequest;
    var vidRequestResponse;
    var returnArray = new Array(4);

    vidRequest = gapi.client.youtube.videos.list({
        part: 'snippet',
        id: VidId
    });
    vidRequest.execute(function(response){
        if(response.pageInfo.totalResults != 0) {
            returnArray[0] = response.result.items[0].snippet.title;
            returnArray[1] = response.result.items[0].snippet.description;
            returnArray[2] = response.result.items[0].snippet.publishedAt;
            //Check for HD thumbnail
            if (response.result.items[0].snippet.thumbnails.maxres.url){
                returnArray[3] = response.result.items[0].snippet.thumbnails.maxres.url
            }
            else {
                returnArray[3] = response.result.items[0].snippet.thumbnails.standard.url;
            }
            console.log(returnArray); //Will log desired return array
        }
    });
    return returnArray; //Not returning desired array
}

从注释中可以看到,数组已正确设置,但未返回该值。

我尝试了什么?
  • 使用从vidRequest.execute()调用的函数中设置的外部变量
  • vidRequest.execute()返回
  • 将响应放入变量中,然后分配数组(给我有关pageInfo为undefined的错误)

  • 注释
  • 似乎是一个异步问题
  • 我需要保留getVidInfo()
  • 在Google API加载
  • 时定义地调用
  • 它似乎可以在初始加载时工作,但是刷新会破坏它
  • 时,所有信息都会记录到控制台

    完整代码

    index.html
    <!DOCTYPE html>
    <html>
    <head>
        <title>YT Test</title>
        <!--My Scripts-->
        <script src="test.js"></script>
    </head>
    
    <body>
        <!-- Load google api last-->
        <script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"> </script>
    </body>
    </html>
    

    test.js
    var apiKey = "[YOUR API KEY]"; //I did set this to my API key
    var latestVidUrl;
    var request;
    var vidId;
    var vidInfo;
    
    function googleApiClientReady() {
        console.log("Google api loaded");
        gapi.client.setApiKey(apiKey);
        gapi.client.load('youtube', 'v3', function() {
            request = gapi.client.youtube.search.list({
                part: 'id',
                channelId: 'UCOYWgypDktXdb-HfZnSMK6A',
                maxResults: 1,
                type: 'video',
                order: 'date'
            });
            request.execute(function(response) {
                if(response.pageInfo.totalResults != 0) {
                    vidId = response.result.items[0].id.videoId;
                    //console.log(vidId);
                    vidInfo = getVidInfo(vidId);
                    console.log(vidInfo);
                }
            });
        });
    }
    
    function getEmbedCode(id){
        var baseURL = "http://www.youtube.com/watch?v="
        return baseURL + id.toString();
    }
    
    function getVidInfo(VidId){
        var vidRequest;
        var vidRequestResponse;
        var returnArray = new Array(4);
    
        vidRequest = gapi.client.youtube.videos.list({
            part: 'snippet',
            id: VidId
        });
        vidRequest.execute(function(response){
            if(response.pageInfo.totalResults != 0) {
                returnArray[0] = response.result.items[0].snippet.title;
                returnArray[1] = response.result.items[0].snippet.description;
                returnArray[2] = response.result.items[0].snippet.publishedAt;
                //Check for HD thumbnail
                if (response.result.items[0].snippet.thumbnails.maxres.url){
                    returnArray[3] = response.result.items[0].snippet.thumbnails.maxres.url
                }
                else {
                    returnArray[3] = response.result.items[0].snippet.thumbnails.standard.url;
                }
                console.log(returnArray); //Will log desired return array
            }
        });
        return returnArray; //Not returning desired array
    }
    

    最佳答案

    我认为问题是您可能尚未处理时返回returnArray。为了弄清楚我的意思,即使您在结尾处添加了return returnArray,实际的请求仍会得到处理,但是代码仍然会继续运行。因此,当最终获得响应并处理代码时,它将正确地写入日志,但是该函数早先已经返回returnArray。如果不测试是否可行,则只要不希望它为null,就可以添加轮询函数,直到returnArray不为null。也许像这样:

    while(returnArray == null) {
        ; }
    return returnArray;
    

    我将对其进行编辑以阐明我的意思:
    function getVidInfo(VidId){
    var vidRequest;
    var vidRequestResponse;
    var returnArray = new Array(4);
    
    vidRequest = gapi.client.youtube.videos.list({
        part: 'snippet',
        id: VidId
    });
    vidRequest.execute(function(response){
        if(response.pageInfo.totalResults != 0) {
            returnArray[0] = response.result.items[0].snippet.title;
            returnArray[1] = response.result.items[0].snippet.description;
            returnArray[2] = response.result.items[0].snippet.publishedAt;
            //Check for HD thumbnail
            if (response.result.items[0].snippet.thumbnails.maxres.url){
                returnArray[3] = response.result.items[0].snippet.thumbnails.maxres.url
            }
            else {
                returnArray[3] = response.result.items[0].snippet.thumbnails.standard.url;
            }
            console.log(returnArray); //Will log desired return array
        }
    });
    
    while(returnArray == null) {    //Create busy loop to wait for value
        ; }
    
    return returnArray;
    

    }

    07-24 17:16