从 javascript 中的 API 获取电影数据

fetch movie data from API's in javascript

我有一个 json 超过 15k 部电影的对象,其中包含像这样的 IMDb ID

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

我希望用来自其他 api 的

的数据来完成此数据

我的问题是:使用此 api 中的数据来完成我的数据的最有效方式是什么?
我计划只 运行 这个程序一次并存储结果,这样它就可以遵守 api 限制。

我的第一个想法是做这样的事情

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

感谢您提供的任何帮助:-)

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

这项工作具有 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.