简体   繁体   中英

How to run AJAX in a loop synchronously(block before next iteration)?

I want to run AJAX in a loop as below, but make sure that the ajax call finishes before progressing to the next loop iteration.

for (var i = 1; i < songs.length; i++) {
  getJson('get_song/' + i).done(function(e) {
    var song = JSON.parse(e);
    addSongToPlaylist(song);
  });
}

I know how to accomplish this with countdownlatches or event listeners in java, but have no idea how to do this in javascript.

Because I have of other AJAX calls going on at the same time, I can't use the async=false parameter.

Thanks in advance.

You could do it this way.

(function loop(i) {
  if(i < songs.length) getJson('get_song/' + i).done(function(e) {
    var song = JSON.parse(e);
    addSongToPlaylist(song);
    loop(i + 1);
  });
})(1);

Alternatively you can also use Async.js https://github.com/caolan/async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM