0

For example we've this code:

$.each([1, 2, 3], function(key, val) {
  gear(val);
});

function gear(params) {
   var values = {1: 'abc', 2: 'cba', 3: 'acb'};
   query(values[params]);
}

function query(settings) {
   $.ajax({
     ...
     settings
     ...
   })
}

How can i wait until every iteration will completed and call something yet?

1
  • 1
    You can put $.each in a function and pass a callback function to it and call it once each is over Commented Nov 8, 2015 at 6:10

3 Answers 3

2

You can use .reduce() to iterate the array and jQuery ajax promises to sequence the function calls:

[1, 2, 3].reduce(function(p, item) {
    return p.then(function() {
        return gear(item);
    });
}, $.Deferred().resolve()).then(function() {
    // everything done here
});

function gear(params) {
    var values = {1: 'abc', 2: 'cba', 3: 'acb'};
    return query(values[params]);
}

function query(settings) {
   return $.ajax({
     ...
     settings
     ...
   })
}

This will sequence the ajax calls so the next one doesn't start until the prior one is done.

In both gear() and query(), you return the promise that $.ajax() already returns.

Then, you use .reduce() to iterate the array where you accumulate a promise. You pass in an initially resolved promise and then each item from the array adds a .then() onto the end of the chain.


If you wanted to run all the Ajax calls at the same time and then just get a notification when they are all done, you could do this:

$.when.apply($, [1, 2, 3].map(function(item) {
    return gear(item);
})).then(function(r1, r2, r3) {
    // everything done here
    // results are in arguments[0], arguments[1], ... arguments[n]
});

function gear(params) {
    var values = {1: 'abc', 2: 'cba', 3: 'acb'};
    return query(values[params]);
}

function query(settings) {
   return $.ajax({
     ...
     settings
     ...
   })
}
Sign up to request clarification or add additional context in comments.

6 Comments

Hard to get one's head around deferred but likely the cleverest method. I prefer using the .done/success to iterate since it is lighter on the brain :)
@mplungjan - .then() is the ES6 promise standard. jQuery already supports it, so I use the standard rather than the jQuery proprietary methods. Deferreds/Promises are THE method to manage and coordinate multiple async operations. May as well start learning them now.
Thank you, but it's really 'Hard to get ones head around' :D I have tried use $.when and $.then but without results, can i use they here?
@jfriend00 - I agree - I just wonder how many of the SO askers grok it enough to dare use it :)
@mplungjan - Promises are a powerful tool. They do require learning. But just because they require learning doesn't mean you should avoid them. Hands-down, they are the best way to manage and coordinate multiple asynchronous operations.
|
0
var deferreds = [];
$.each([1, 2, 3], function(key, val) {
  gear(val);
});

function gear(params) {
   var values = {1: 'abc', 2: 'cba', 3: 'acb'};
   query(values[params]);
}

function query(settings) {
   deferreds.push($.ajax({
     ...
     settings
     ...
   }));
}
$.when.apply($, deferreds).done(function(){
  // do something here
});

2 Comments

This runs all the ajax calls at once, not in sequence one after the other. The OP asked to wait til one iteration was done before starting the next.
"How can i wait until every iteration will completed". If I understood the question right that is exactly what was asked. Call the function when all ajax requests succeed.
-1

Below is an example of achieving it.

function iterate(callback) {

  $.each([1, 2, 3], function(key, val) {
    gear(val);
  });
  
  callback();
}

function gear(params) {
  var values = {
    1: 'abc',
    2: 'cba',
    3: 'acb'
  };
  print(values[params]);
}

function print(str) {
  document.write(str + "<br />")
}

function notifyComplete(){
  print("Completed.")
}

iterate(notifyComplete);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

2 Comments

You miss the async and PLEASE do not use document.write - use console or add to some message div
@Rajesh, Unfortunately, your example is not async.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.