Giphy API 乱序调用返回结果

Giphy API Call Returning Results out-of-order

我正在使用对 Giphy 的 API 调用来循环遍历字符串数组和字符串中每个单词的 return Gif。

它正在运行,但显示的结果乱序。

数组的开头是:"STATELY, PLUMP BUCK MULLIGAN CAME FROM THE STAIRHEAD"

结果显示如下:Plump Mulligan Came Buck...你明白了...

代码如下:

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

  })
};

知道结果乱序的原因吗?

两个选项

尽可能快地发出所有请求,但按顺序处理结果

$.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 returns a 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());