【问题标题】:Waiting until all ajax calls are finished not working with $.when等到所有 ajax 调用完成后才使用 $.when
【发布时间】:2017-06-17 16:36:15
【问题描述】:

我试图在所有 ajax 调用完成后调用一次函数。下面的 $.when 被空的 promise 数组调用得太快了。 searchRecommendations() 在之前的几次$.ajax 调用的成功中被调用了几次。这能以某种方式负责吗?

var MAX = 2; //Maximum levels queried
var ARTISTS = [];  //Multidimensional array with the number of potential 'artists' i.e. compare Madonna, to Beethoven to Eminem to nth-artist
var RELEVENT_ARTISTS = 2; //Number of relevent artists added to the list for each new artist 
var promises = []; 

 $(function(){
    init(0);
 })


   function init(i){
   for(var i; i<1; i++){

        console.log('searchArtists for relevant artist '+$('input')[i].value)   
        var artist = $('input')[i].value;
        $.ajax({
            url: 'https://api.spotify.com/v1/search',
            data: {
                q: artist,
                type: 'artist'
            },
                success: function (response) {
                    console.log(response.artists.href);
                    searchRecommendations(response.artists.items[0].id, 0)  
                    //nextLevel(0)
            }
        });


    }
    //console.log(ARTISTS)  
    //getMatches(ARTISTS)   
}



function searchRecommendations(artist, depth) {
            console.log(' ')                
            console.log('searchRecommendations '+artist+ ' '+ depth )   
            if(depth == MAX){ return console.log('max reached '+depth) } else {
                    promises.push(
                        $.ajax({
                            url: 'https://api.spotify.com/v1/artists/' + artist + '/related-artists',
                            data: {
                                type: 'artist',
                            },
                            success: function (response) {

                                console.log('RESPONSE');
                                console.log(response)
                                for(var r=0; r<RELEVENT_ARTISTS; r++){
                                    console.log(response.artists[r].name)
                                    var obj = { 'artist' : response.artists[r].name,  'level':(depth+1)*5 } 

                                    ARTISTS.push(obj)

                                    searchRecommendations(response.artists[r].id, depth+1)  //Recursion
                                }
                            }       
                        })
                    )
            }   
}





$.when.apply(undefined, promises).done(function() {
    convert_artists_to_nodes_and_links(ARTISTS)
    console.log( 'this is being called too soon')
    console.log( promises )
})

How to wait until jQuery ajax request finishes in a loop?

【问题讨论】:

  • searchRecommendations 在哪里调用? MAXARTISTS 在哪里定义?你为什么尝试从searchRecommendationsreturnsetTimeout
  • 你可以试试.ajaxStop()它会等待所有的Ajax调用完成。这是文档:api.jquery.com/ajaxStop
  • 您拥有的代码将在一个空的promises 数组中等待...如果稍后通过某种方式调用该函数,$.when 不会神奇地“重新运行”...承诺不能替代事件驱动代码
  • @guest271314 即使没有 setTimeout 我也有这个问题。
  • OK ... 那么为什么你认为$.when 会等待init 完成后再执行呢? ...您的代码就像让var promises = []; 立即 跟在$.when... 之后,然后是您的函数定义...正如我之前所说,$.when 不检查以查看承诺何时有数据在里面......它怎么知道什么时候都被添加了?

标签: javascript jquery ajax promise .when


【解决方案1】:

好的,对你的代码进行大的重构,但我认为这会做你想要的 - 抱歉我无法测试它 - 我会尝试慢慢添加 cmets 来解释代码

function init(i) {
    // $('input.artist') - as I can't see your HTML, I would recommend adding cclass='artist' to inputs that you want to process
    // [].map.call($('input.artist'), function(artist, i) { - iterate through the inputs, calling the function which returns a promise
    // artistP will be an array of Promises
    var artistsP = [].map.call($('input.artist'), function(artist, i) {
        console.log('searchArtists for relevant artist ' + $('input')[i].value)
        var artist = $('input')[i].value;
        // return the promise returned by $.ajax
        return $.ajax({
            url: 'https://api.spotify.com/v1/search',
            data: {
                q: artist,
                type: 'artist'
            }
        })
        // the returned promise needs to wait for the promise returned by searchRecommendations
        .then(function(response) {
            console.log(response.artists.href);
            return searchRecommendations(response.artists.items[0].id, 0);
        });
    });
    // wait for the promises to complete and we're done
    $.when.apply($, artistsP).done(function() {
        convert_artists_to_nodes_and_links(ARTISTS)
    });
}

function searchRecommendations(artist, depth) {
    console.log('searchRecommendations ' + artist + ' ' + depth)
    if (depth == MAX) {
        // just return undefined to stop the recursion
        return console.log('max reached ' + depth);
    } else {
        // return a promise
        return $.ajax({
            url: 'https://api.spotify.com/v1/artists/' + artist + '/related-artists',
            data: {
                type: 'artist',
            }
        })
        // the promise needs to wait for the recursed artists
        .then(function(response) {
            // create an array of promises to wait on
            var promises = response.artists.map(function(artist) {
                console.log(artist.name)
                var obj = {
                    'artist': artist.name,
                    'level': (depth + 1) * 5
                }
                ARTISTS.push(obj)
                return searchRecommendations(response.artists[r].id, depth + 1) //Recursion
            });
            // return a promise that waits for all the "sub" requests
            return $.when.apply($, promises);
        });
    }
}

【讨论】:

  • 我收到jQuery.Deferred exception: #&lt;r&gt; is not a function TypeError: #&lt;r&gt; is not a function
  • 是的,需要进行一些修复 - 我有点搞砸了
  • 谢谢。 thinkful-niko.github.io/six/sixd3 它有效。我会深入研究并找出确切原因。
猜你喜欢
  • 2013-10-14
  • 1970-01-01
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多