Giphy API调用返回结果无序

时间:2018-05-10 05:01:23

标签: javascript jquery ajax giphy

我使用对Giphy的API调用来遍历字符串数组并为字符串中的每个单词返回Gif。

它正在运作,但结果显示无序。

阵列的开头是:" STATELY,PLUMP BUCK MULLIGAN CAME from the STAIRHEAD"

结果显示:丰满的穆里根来了巴克......你明白了......

以下是代码:

    var chapter = "STATELY, PLUMP BUCK MULLIGAN CAME FROM THE STAIRHEAD," 

let words = chapter.split(" ");

for (i=0; i<words.length; i++){

    let word = words[i];

    var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + word + "&api_key=<MY API KEY>";
    $.ajax({
        url: queryURL,
        method: 'GET'
        })
        .done(function(response) {


                var results = response.data;

                    var gifDiv = $('<div/>');
                    var gif = $('<img/>');
                    gif.addClass('myImg');
                    gif.attr('src', results[0].images.fixed_height.url);
                    gif.attr('data-animate', results[0].images.fixed_height.url)
                    gif.attr('data-state', 'still');
                    gifDiv.append(gif);

                    gifDiv.append('<h1>' + word + '</h1>');

                    gifDiv.appendTo($('#gifs-here'));

  })
};

为什么结果出现故障的任何想法?

1 个答案:

答案 0 :(得分:1)

两个选项

尽快提出所有请求,但系列处理结果

$.when(...chapter.split(" ").map(word => {
    var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + word + "&api_key=<MY API KEY>";
    return $.ajax({
        url: queryURL,
        method: 'GET'
    });
})).then((...responses) => {
    responses.forEach(response => {
        var results = response.data;
        ..... rest of your done code .....
    });
})

发出请求并按顺序处理结果,每个请求等待前一个处理完成

chapter.split(" ").reduce((p, word) => {
    return p.then(() => {
       var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + word + "&api_key=<MY API KEY>";
        return $.ajax({
            url: queryURL,
            method: 'GET'
        }).then(response => {
            var results = response.data;
            ..... rest of your done code .....
        });
    });
}, $.when())

为了完整性,因为jQuery $ .ajax返回thenable ...你可以使用Promises

Promise.all(chapter.split(" ").map(word => {
    var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + word + "&api_key=<MY API KEY>";
    return $.ajax({
        url: queryURL,
        method: 'GET'
    });
})).then(responses => {
    responses.forEach(response => {
        var results = response.data;
        ..... rest of your done code .....
    });
})

chapter.split(" ").reduce((p, word) => {
    return p.then(() => {
       var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + word + "&api_key=<MY API KEY>";
        return $.ajax({
            url: queryURL,
            method: 'GET'
        }).then(response => {
            var results = response.data;
            ..... rest of your done code .....
        });
    });
}, Promise.resolve());