4

I want to call multiple APIs inside a loop (ex: $.each). I can do this with async:false mode but it makes the script lag. How to achieve this in synchronized mode? Just ignoring async option makes only the last element in list to be sent to api calls.

$.each(lists, function(index, value) {

            channel = lists[index].channel;
            list = lists[index].list;

            $.ajax({
                url : 'api.php?list=' + list + '&from=' + from + '&to=' + to,
                dataType : 'json',
                async : false,
                success : function(data) {
                    obj = data;

                    $.ajax({
                        url : 'api.php?list=' + list + '&from=' + from + '&to=' + to + '&action=sender',
                        dataType : 'json',
                        async : false,
                        success : function(data) {

                            obj['senders'] = data.msg;
                            CommonContainer.inlineClient.publish(channel, obj);

                        }
                    });

                }
            });

        });
3
  • 1
    stackoverflow.com/questions/13250746/… Commented Jan 8, 2013 at 8:31
  • what do you mean makes only the last one sent to api calls? looking at _.after may be useful, you can create a function that will run after it has been called X amount of times. I use it if I am making, say, 5 AJAX calls and want something to run if they all succeed. - if you want an example let me know and i can throw one together Commented Jan 8, 2013 at 8:35
  • 1
    I disagree with the duplicate. The problem here was a declaration bug making the closure unable to protect the variables. Commented Jan 8, 2013 at 8:41

1 Answer 1

5

That's because channel and list are global (or declared out of the scope of the function passed to $.each) and thus aren't protected by the closure.

Use this :

  var channel = lists[index].channel;
  var list = lists[index].list;

You should also declare obj as

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

Comments

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.