0

For example we've following code:

var data = [obj, obj, obj];

function handler(k, v) {
  ...
  check(v, function() {});
}

function check(params, callback) {
  ...
  request(options, callback);
}

function request(opts, callback) {
  $.ajax({
    ...
    opts
    ...
    callback
  });
}

$.each(data, handler);

How can we wait for done $.each and call some function? For example, something look like:

$.when($.each(data, handler)).then(alert(1));

I can not find solution.

P.S. We can not know length of data.

P.S. this is not duplicate because code apologize using promises or something pretty

1

2 Answers 2

0

I suggest looking into the q library and start using promises for this problem. You can also include each callback in the previous one, creating your first Pyramid of Doom.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to return the jqXHR objects and stack them up in an array with $.map:

var data = [obj, obj, obj];

function handler(v, i) {
  ...
  return check(v, function() {});
}

function check(params, callback) {
  ...
  return request(options, callback);
}

function request(opts, callback) {
  return $.ajax({
    ...
    opts
    ...
    callback
  });
}

$.when($.map(data, handler)).then(function(){

  });

4 Comments

Nice solution, but not working for me: then can't get results of new var after executing
I don't know what you mean by "then can't get results of new var". You want to reach the resolved values of each individual deferred object? They are part of the arguments object inside the then handler.
Oh, my bad, look: function handler have an array of all results, and when i use $.then(function(){console.log(array of results)}) it's empty because was executed before end of loop
Well, sounds like it's part of the omitted code and another type of error (maybe your results aren't global). You shouldn't be dealing with your results this way, like I said before, you'd need to grab them from the arguments object inside the then handler.

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.