0

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

它正在工作,但结果显示不正常。

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

结果显示如下:Plump Mulligan Come 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'));

  })
};

任何想法为什么结果不正常?

4

1 回答 1

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());
于 2018-05-10T05:12:45.917 回答