earthQuake
earthQuake

Reputation: 106

Wait until all nested google api requests done

I want to gather some data from google Youtube by using its api. Here I trying to retrieve snippets (gapi.client.youtube.search.list request) in a loop for each keyword. And then for each snippet i trying to load its statistics with another request (gapi.client.youtube.videos.list). After all requests is completed i want to handle gathered data with ajax call;

The problem is that my ajax call starts to early, before stats requests done. Here i used batch requests. By the way please explain how to grab data from their responses. They are with some random ids.enter image description here

Hope i understand clear what i want. Please explain how can i chain my requests to make possible do something after all work is done.

Here is the code:

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

This is what i get in result enter image description here

Upvotes: 1

Views: 689

Answers (1)

manonthemat
manonthemat

Reputation: 6251

Promises are your friends. You can create an array of promises and use Promises.all() to return another promise that you can then work with.

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

Upvotes: 1

Related Questions