最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - GET request inside of a loop in JavaScript - Stack Overflow

programmeradmin1浏览0评论

So, my code looks something like

for(int n = 0; n < object.length; n++){
  /*Other code */
  $.get(...,function(data){
    //do stuff
  });}

Now, the other code executes multiple times like it should. However, when the get mand is ran, it is only ran once and that is when n reaches the object.length. This causes all sorts of errors. n is only being incremented in the for loop.

Can you not loop get/post mands? Or if you can, what am doing wrong? Thanks.

So, my code looks something like

for(int n = 0; n < object.length; n++){
  /*Other code */
  $.get(...,function(data){
    //do stuff
  });}

Now, the other code executes multiple times like it should. However, when the get mand is ran, it is only ran once and that is when n reaches the object.length. This causes all sorts of errors. n is only being incremented in the for loop.

Can you not loop get/post mands? Or if you can, what am doing wrong? Thanks.

Share Improve this question edited Jun 14, 2015 at 6:26 maček 77.9k37 gold badges171 silver badges200 bronze badges asked Jun 14, 2015 at 6:12 Zach BabbittZach Babbitt 1271 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

The for-loop won't wait for the $.get call to finish so you need to add some async flow control around this.

Check out async.eachSeries. The done callback below is the key to controlling the loop. After the success/fail of each $.get request you call done(); (or if there's an error, you call done(someErr);). This will advance the array iterator and move to the next item in the loop.

var async = require("async");
var list = ["foo", "bar", "qux"];

async.eachSeries(list, function(item, done) {

  // perform a GET request for each item in the list
  // GET url?somevar=foo
  // GET url?somevar=bar
  // GET url?somevar=qux
  $.get(url, {somevar: item}, function(data) {
    // do stuff, then call done
    done();
  });

}, function(err) {
  if (err) {
    throw err;
  }
  console.log("All requests are done");
});

Do you want all the get requests to be done at the same time or one after the other? You can do all at once with a forEach loop. forEach works better than a normal for loop because it gives you a new instance of elem and n in each iteration.

object.forEach(function(elem, n) {
  /*Other code */
  $.get(...,function(data){
    //do stuff
  });
});

But if you want to do the requests one after the other you could do it this way.

(function loop(n) {
  if(n >= object.length) return;
  /*Other code */
  $.get(...,function(data){
      //do stuff
      loop(n + 1);
    });
})(0);
发布评论

评论列表(0)

  1. 暂无评论