等到所有嵌套的google api请求完成

时间:2016-02-09 19:03:52

标签: javascript ajax youtube google-api promise

我想通过使用它的api从谷歌Youtube收集一些数据。在这里,我尝试在每个关键字的循环中检索片段( gapi.client.youtube.search.list请求)。然后,对于每个片段,我尝试使用其他请求( gapi.client.youtube.videos.list )加载其统计信息。完成所有请求后,我想用ajax调用处理收集的数据;

问题是我的ajax调用在stats请求完成之前就开始了。 在这里我使用了批量请求。请顺便解释如何从他们的回复中获取数据。它们带有一些随机ID。enter image description here

希望我明白我想要的东西。请解释我如何将我的请求链接起来,以便在完成所有工作后做一些事情。

以下是代码:

var stats = [];
var videoData;
var keys = ['car crash', 'cats', 'fail'];

function Init() {
    gapi.client.setApiKey("myApiKey");
    gapi.client.load("youtube", "v3", function () {
        console.log("api is ready");

        var keys = GetKeyWords();
        RetrieveVideos(keys);
    });
}

function RetrieveVideos(keys) {

    var videoSearchBatch = gapi.client.newBatch();

    for (n = 0; n < keys.length; n++)
    {
        var videoSearchRequest = MakeRequestForVideos(keys[n]);
        videoSearchBatch.add(videoSearchRequest);
        videoSearchRequest.then(function (response) {
            GetStatistics(response);
        });
    }
    
    //Here i want to make an ajax call and handle gathered data
    videoSearchBatch.then(function (response) {
        videoData = response.result.items;
        $.ajax({
            url: '/ajax/ajaxHandler.php',
            type: 'post',
            data: {'data': videoData, 'stats': stats},
            success: function () {
                console.log("OK!");
            }
        });
    });
}

function MakeRequestForVideos(key) {
    return gapi.client.youtube.search.list({
        part: "snippet",
        type: "video",
        q: key,
        maxResults: 50,
        order: "viewCount",
        publishedAfter: "2007-01-01T00:00:00Z"
    });
}

function GetStatistics(response) {
    
    var statsBatch = gapi.client.newBatch();

    for (i = 0; i < response.result.items.length; i++)
    {
        var statsRequest = gapi.client.youtube.videos.list({
            part: "statistics",
            id: response.result.items[i].id.videoId
        });

        statsBatch.add(statsRequest);
        statsRequest.then(function (response) {
            stats.push(response.result.items[0].statistics);
        });
    }

    statsBatch.then(function (response) {
        console.log(response.result);
    });
}

这就是我得到的结果 enter image description here

1 个答案:

答案 0 :(得分:1)

承诺是你的朋友。您可以创建一个promises数组,并使用Promises.all()返回另一个可以使用的promise。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all