Javascript: is there a better way to execute a function after x amount of async database/ajax calls

≡放荡痞女 提交于 2019-12-06 07:31:18

You have to use JQuery $.Deferred object to sync them. Look at this article Deferred Docs

You can use in this way:

$.when(
   $.ajax({ url : 'url1' }),
   $.ajax({ url : 'url2' }) // or even more calls
).done(done_callback).fail(fail_callback);

I would do something like this:

make a function that besides the parameters that you pass to fetchData also gets the index within arrParams, then in a loop call that function for every element. In the success function set processed in your element to true, and check if "you're the last" by going through the array and see if all the rest is true as well.

A bit of optimization can be if you make a counter:

var todo = arrParams.length;

and in the success you do:

if (--todo == 0) {
   callback(...)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!