Multiple asynchronous Ajax calls inside each loop in jQuery

I want to call several APIs inside a loop (for example: $ .each). I can do this using async:false mode, but it does lag the script. How to achieve this in synchronous mode? Just ignoring the async option allows you to send only the last item in list 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); } }); } }); }); 
+4
source share
1 answer

This is because channel and list are global (or declared outside the scope of the function passed in $.each ) and thus are not protected by closure.

Use this:

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

You must also declare obj as

  var obj = ... 
+5
source

All Articles