fetch movie data from API's in javascript

2019-06-02 05:28发布

I have a json object of >15k movies containing IMDb ID's like this

0: ObjectID: "1."
   IdIMDb: "tt2322441"
   Title: "Fifty Shades of Grey"
   Year: 2015
1: ObjectID: "2."
   IdIMDb: "tt1617661"
   (...)

And I'm looking to complete this data with data from other api's

My question is: what is the most efficient manner to complete my data with data from this api ?
I plan to run this program only once and store the result so it can respect api restrictions.

My first idea was to do something like this

data.forEach(function (d, i) {
    d.Poster = OMDbApi(d.IdIMDb);
    ...
}

function OMDbApi(i) {
    $.ajax({
        url:"http://www.omdbapi.com/?i="+i+"&plot=short&r=json",
        crossDomain: true,
        dataType: "jsonp",
        success: function (response) {
            return response.Poster;
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            error = 1;
        } 
    });
}

Thank you for any help you can provide :-)

1条回答
唯我独甜
2楼-- · 2019-06-02 05:45
var totalCalls = 15000;
    var calls = 0;
    data.forEach(function (d, i) {
    OMDbApi(I, d.IdIMDb); //posterCall
}

function OMDbApi(index, id) {
    $.ajax({
        url:"http://www.omdbapi.com/?i="+id+"&plot=short&r=json",
        crossDomain: true,
        dataType: "jsonp",
                    dataObj : index,
        success: function (response) {
            window.data[this.dataObj].Poster = response.poster;
                            calls++;
                            if (calls == totalCalls)
                            {
                               alert("We're done");
                            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            error = 1;
        } 
    });
}

This work with the asynchronous nature of Ajax.

You might want to keep track of all the requests you make and show a message when all the requests are finished. I've added a simple example of how to keep track. The essence is that you know how many calls you're going to make. So you need to count the amount of ids and multiply that amount by the calls needed to complete the date. For example: every object has to make three calls to complete the data; poster, director and runtime. There are 14500 objects. This will result in a total of 3*14500 = 43500 calls. The script add 1 to the variable calls when a call is completed. When the calls equals the totalCalls an alert is shown.

查看更多
登录 后发表回答