Serializing the function call - javascript

I have a javaScript object having some value. I need to call a function as many times as the object has the value. Look at the code snipet
for(var i=0; i < scroll["altscroll"]; i++){
more_alt_leftajaxsearchcategory(0, 0, element=false, back = true);
}
The called function loads some element through ajax method and append it to the body.
The problem is that when loop executes the function is called instantaneously but the called function returned result not in the order expected. For example if function is called 3 times and if returned result in last calling is smaller in size then it appends first in the body after that the other returned result is appended.
Can we serialize the function call so that it does not call another function until the first one completes.
The called function code snipet:
var pageCount = 1;
function more_leftajaxsearchcategory(locval,pageid, element, back){
var offsetCount = pageCount * 10;
var dataString = jQuery("#leftformid").serialize();
jQuery.ajax({
url:"<?php echo admin_url('admin-ajax.php'); ?>",
type:'POST',
data: 'action=leftmenusearchcategory'+'&locationval='+locval+'&numb='+offsetCount+'&'+dataString,
beforeSend: function(){jQuery('body').append('<p class="overBck"><img alt="Loading..." src="<?php bloginfo('template_url'); ?>/images/ajax-loader.gif" style="margin-top:25%;"></p>'); },
success:function(results, status)
{
jQuery(".book_results").append(results);
if(results == 'Sorry no results found. Please search again.'){
jQuery('.sidebar_loadMore').hide();
pageCount =1;
}
jQuery('.overBck').remove();
short_deals_attr();
}
});
pageCount++;
}
I have removed the unnesessory code. You can also look at the live site Bestofthebrunch

The best possible way that I found to serialize the function call in this case is a recursive call on the success of the previous one.
more_alt_leftajaxsearchcategory(0, 0, element=false, back = true, scroll["altscroll"] -1);
and updated the called function on success of Ajax by
if(back && loadtimes > 0){
more_alt_leftajaxsearchcategory(0, 0, element=false, back = true, loadtimes-1 );
}
like this...
var pageCount = 1;
function more_leftajaxsearchcategory(locval,pageid, element, back, times){
var offsetCount = pageCount * 10;
var dataString = jQuery("#leftformid").serialize();
jQuery.ajax({
url:"<?php echo admin_url('admin-ajax.php'); ?>",
type:'POST',
data: 'action=leftmenusearchcategory'+'&locationval='+locval+'&numb='+offsetCount+'&'+dataString,
beforeSend: function(){jQuery('body').append('<p class="overBck"><img alt="Loading..." src="<?php bloginfo('template_url'); ?>/images/ajax-loader.gif" style="margin-top:25%;"></p>'); },
success:function(results, status)
{
jQuery(".book_results").append(results);
if(results == 'Sorry no results found. Please search again.'){
jQuery('.sidebar_loadMore').hide();
pageCount =1;
}
if(back && loadtimes > 0){
more_alt_leftajaxsearchcategory(0, 0, element=false, back = true, loadtimes-1 );
}
jQuery('.overBck').remove();
short_deals_attr();
}
});
pageCount++;
}
In this method the function more_leftajaxsearchcategory is not called immediately without caring of the response of previous call. The function is called only when the first one get the response.

You have to add addtional param to pass in a callback that would be called when the ajax complete its work, then you can achieve something like this.
I'd use setTimeout with random length to fake as an ajax call:
var inserial = function(times) {
var count = 0;
function delay() {
var cur = count;
var length = Math.floor((Math.random() * 7) + 1) * 500;
$('<div>').text('#' + cur + ' will complete in ' + length).appendTo($('body'));
setTimeout(function() {
// Somthing in success ajax callback.
$('<div>').text('#' + cur + 'Done.').appendTo($('body'));
// Then call it to start next ajax load.
done();
}, length);
count++;
}
function done() {
if (count === times) {
$('<div>').text('All done').appendTo($('body'));
return;
}
delay();
}
// Your function, which aceepts a callback function.
delay();
};
inserial(5);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
Or if you love to embrace new techs, try Promise, it's a ES2015 feature while there are already libs implements it, it makes you easy to start all loading process at the same time, while keeps the order of the elements.
But you may need to learn its idea first, JavaScript Promises should be a good start.
var delay = function(id, cb) {
var length = Math.floor((Math.random() * 7) + 1) * 500;
$('<div>').text('#' + id + ' will complete in ' + length).appendTo($('body'));
// Wrap you ajax into promise.
return new Promise(function(resolve, reject){
setTimeout(function() {
// This will be called in ajax's success callback.
resolve(id);
}, length);
});
};
var i, arr = [];
// These function will all start to execute.
for (i = 0; i < 5; ++i) {
arr[i] = delay(i);
}
// But their results will be guranteed to put in order.
var sequence = Promise.resolve();
arr.reduce(function(seq, item) {
//
return seq.then(function() {
// the promise return from delay will get the resolved id as parameter.
return item;
}).then(function(id) {
// This is the commands in origin ajax's succes callback.
$('<div>').text('#' + id + 'Complete.').appendTo($('body'));
});
}, sequence);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.0/es6-shim.js"></script>

Related

code after the $.each execute before the function finished executing

I have an function inside it i am using $.each method. I want to call another function alertMsg() after $.each completely executed. But when i use breakpoints i can see that before finishing the $.each method it executes the alertMsg function. why? how to solve it.
function test(hospitalJson,blockJson){
$.each(hospitalJson.organisationUnits, function (i, curr_hos) {
if (curr_hos.id == orgUnit.id) {
var stringPath=[];
stringPath= curr_hos.path.split("/");
outerloop:
for(var i=0;i<stringPath.length;i++){
for(var j=0;j<blockJson.length;j++){
if(stringPath[i]==blockJson[j].id){
document.getElementById('blockID').innerHTML = blockJson[j].id;
break outerloop;
}
}
}
// to get district name
var districtNameURL="../api/organisationUnits.json?fields=name&filter=id:in:[" + curr_hos.path.split("/")[4] + "]" ;
$.get(districtNameURL,function(district){
districtName=district.organisationUnits[0].name;
console.log(districtName);
document.getElementById('districtID').innerHTML = districtName;
});
alertMsg = 1;
return false;
}
});
//this message execute before finishing $.each
alert(alertMsg);
}
Due to the fact that $.each has multiple AJAX calls inside, you need to create an array containing Promise objects that need to be resolved . Since you may not know the exact size of the parsed JSON object and jQuery $.when cannot handle arrays you need to extend it's functionality.
function test(hospitalJson, blockJson) {
var deferreds = [];
$.each(hospitalJson.organisationUnits, function(i, curr_hos) {
//...
deferreds.push(
$.get(districtNameURL, function(district) {
districtName = district.organisationUnits[0].name;
console.log(districtName);
document.getElementById('districtID').innerHTML = districtName;
}));
}
return deferreds;
});
}
var resolveData = test(hospitalJson, blockJson);
$.when.apply(null, resolveData).done(function() {
alert(alertMsg);
});
JSfiddle demo
Change:
$.get(districtNameURL,function(district){
districtName=district.organisationUnits[0].name;
console.log(districtName);
document.getElementById('districtID').innerHTML = districtName;
});
To:
$.ajax({
url: districtNameURL,
type: "GET",
async: false
})
.success(function (district) {
districtName = district.organisationUnits[0].name;
console.log(districtName);
document.getElementById('districtID').innerHTML = districtName;
});
This will stop the get action being asynchronous and therefore your logic will be processed in the expected order.

JavaScript offset/pagination issue

I am calling to my local API and trying to do it in a pagination style. I have n pictures that I want divided over n / 4 rows (4 pictures per row).
So therefor, I am calling to my API, images/count,offset. But somehow I keep on getting the same results in console.log, namely the first four images.
$(document).ready(function() {
var offset = 0;
var timesToRun = $('.container').data('rows');
var images = [];
for(var i = 1; i <= timesToRun; i++) {
$.ajax('http://192.168.10.11/images/4,' + offset, {
error: function(err) {
console.log(err);
},
method: 'GET',
success: function(data) {
console.log('http://192.168.10.11/images/4,' + offset);
offset = offset + 4;
var currentSet = [];
currentSet.push(data);
console.log(currentSet);
}
});
}
});
In Laravel I am pulling the number of images like so:
public function selectWithOffset($count, $offset)
{
$selectionOfImages = \DB::table('images')->skip($offset)->take($count)->get();
return response()->json($selectionOfImages);
}
When I click the links I do receive the expected response.
What might go wrong here?
The problem is within your JavaScript. $.ajax is asynchronous by default.
The for loop will complete before any success callback of $.ajax is called, and this is the place where you increase the offset.
You have to options to fix this:
1. Make $.ajax synchronous
Add async: false to the $.ajax options.
$.ajax('http://192.168.10.11/images/4,' + offset, {
error: function(err) {
console.log(err);
},
async: false,
method: 'GET',
success: function(data) {
// ...
}
});
2. Increment offset outside of the success callback
for(var i = 1; i <= timesToRun; i++) {
$.ajax('http://192.168.10.11/images/4,' + offset, {
// ...
});
// Increment offset
offset += 4;
}

Adding more than one AJAX call to a Script

I need to add a function to my script that gets the current server time.
I use the PHP file below to get the server time in milliseconds.
<?php
date_default_timezone_set('Europe/London');
$serverTime = round(microtime(true) * 1000);
echo json_encode($serverTime);
?>
Then i would like to add an Ajax request to 'get' serverTime.PHP and put it into a variable so that i can calculate the time before something ends correctly.
I currently get the clients time by using this
var now = new Date ().getTime();
Now i want to remove that line and add my ajax request.
I have tried adding the following code into the script but i can not get it to execute
function now ()
{
this.ajax.open('GET', 'serverTime.php',
true);
this.ajax.send(null);
if (this.ajax.readyState != 4) return;
if (this.ajax.status == 200)
{
// get response
var now = eval ('('+this.ajax.responseText+')');
}
}
The end result being the variable 'NOW' contains the output of serverTime.PHP
Here is my script, i have tried to add anothert ajax get request in various ways but i cant get it to function correctly.
$.ajaxSetup({
type: 'GET',
headers: { "cache-control" : "no-cache" }
});
var PlayList = function (onUpdate, onError)
{
// store user callbacks
this.onUpdate = onUpdate;
this.onError = onError;
// setup internal event handlers
this.onSongEnd = onSongEnd.bind (this);
// allocate an Ajax handler
try
{
this.ajax = window.XMLHttpRequest
? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// fatal error: could not get an Ajax handler
this.onError ("could not allocated Ajax handler");
}
this.ajax.onreadystatechange = onAjaxUpdate.bind(this);
// launch initial request
this.onSongEnd ();
// ------------------------------------------
// interface
// ------------------------------------------
// try another refresh in the specified amount of seconds
this.retry = function (delay)
{
setTimeout (this.onSongEnd, delay*5000);
}
// ------------------------------------------
// ancillary functions
// ------------------------------------------
// called when it's time to refresh the playlist
function onSongEnd ()
{
// ask for a playlist update
this.ajax.open('GET', 'playlist.php', // <-- reference your PHP script here
true);
this.ajax.send(null);
}
// called to handle Ajax request progress
function onAjaxUpdate ()
{
if (this.ajax.readyState != 4) return;
if (this.ajax.status == 200)
{
// get response
var list = eval ('('+this.ajax.responseText+')');
// compute milliseconds remaining till the end of the current song
var start = new Date(list[0].date_played.replace(' ', 'T')).getTime();
var now = new Date ( ).getTime();
var d = start - now + 6500
+ parseInt(list[0].duration);
if (d < 0)
{
// no new song started, retry in 3 seconds
d = 3000;
}
else
{
// notify caller
this.onUpdate (list);
}
// schedule next refresh
setTimeout (this.onSongEnd, d);
}
else
{
// Ajax request failed. Most likely a fatal error
this.onError ("Ajax request failed");
}
}
}
var list = new PlayList (playlistupdate, playlisterror);
function playlistupdate (list)
{
for (var i = 0 ; i != list.length ; i++)
{
var song = list[i];
}
{
document.getElementById("list0artist").innerHTML=list[0].artist;
document.getElementById("list0title").innerHTML=list[0].title;
document.getElementById("list0label").innerHTML=list[0].label;
document.getElementById("list0albumyear").innerHTML=list[0].albumyear;
document.getElementById("list0picture").innerHTML='<img src="/testsite/covers/' + list[0].picture + '" width="170" height="170"/>';
document.getElementById("list1artist").innerHTML=list[1].artist;
document.getElementById("list1title").innerHTML=list[1].title;
document.getElementById("list1label").innerHTML=list[1].label;
document.getElementById("list1albumyear").innerHTML=list[1].albumyear;
document.getElementById("list1picture").innerHTML='<img src="/testsite/covers/' + list[1].picture + '" width="84" height="84"/>';
document.getElementById("list2artist").innerHTML=list[2].artist;
document.getElementById("list2title").innerHTML=list[2].title;
document.getElementById("list2label").innerHTML=list[2].label;
document.getElementById("list2albumyear").innerHTML=list[2].albumyear;
document.getElementById("list2picture").innerHTML='<img src="/testsite/covers/' + list[2].picture + '" width="84" height="84"/>';
document.getElementById("list3artist").innerHTML=list[3].artist;
document.getElementById("list3title").innerHTML=list[3].title;
document.getElementById("list3label").innerHTML=list[3].label;
document.getElementById("list3albumyear").innerHTML=list[3].albumyear;
document.getElementById("list3picture").innerHTML='<img src="/testsite/covers/' + list[3].picture + '" width="84" height="84"/>';
document.getElementById("list4artist").innerHTML=list[4].artist;
document.getElementById("list4title").innerHTML=list[4].title;
document.getElementById("list4label").innerHTML=list[4].label;
document.getElementById("list4albumyear").innerHTML=list[4].albumyear;
document.getElementById("list4picture").innerHTML='<img src="/testsite/covers/' + list[4].picture + '" width="84" height="84"/>';
$('.nowPlayNoAnimate').each(function() {
$(this).toggleClass('nowPlayAnimate', $(this).parent().width() < $(this).width());
});
}
}
function playlisterror (msg)
{
// display error message
console.log ("Ajax error: "+msg);
//retry
list.retry (10); // retry in 10 seconds
}
Why not use the jquery method ?
function getServerTime() {
var now = null;
$.ajax({
url: "serverTime.php",
dataType: 'JSON',
async: false,
success: function (data) {
now = data;
}
});
return now;
}
You can start as many requests as you want in a browser-portable way.
PS:
you may also want to replace
document.getElementById("list4artist").innerHTML=list[4].artist;
by the shorter
$("#list4artist").html(list[4].artist);
Edit: Add async parameter to make the execution wait for the ajax call to simulate a non-asynchronous function call.
Assuming your service return the date object, you need to add the following line inside the success function (suggested by Clément Prévost):
var now = data;
The success function is an async callback function the triggers after the server return a value.
You should read about Jquery Ajax, it will make your life much easier.

Clean way to make Subsequent AJAX Calls to API based on Data

So I have a conceptual question regarding the cleanest way to make subsequent AJAX calls to an API based on the returned data.
A quick example:
A function, which encompasses the call would look like this:
function makeCall(headers, min, max) {
$.ajax({
headers: headers,
url: "https://coolapi.com/data?begIndex" + min + "&endIndex=" + max + "&begTimestamp=1404198000000&endTimestamp=1409554800000",
type: "GET",
dataType: 'JSON'
});
}
makeCall(headers, 0, 20);
The beg / end index (min/max), determine the amount of data I'll get back in the array. The API will only return a maximum of 20 items in the array, but it will also return me a COUNT of how many items total exist in that array. An example of the data returned is below:
{
count = 133;
result = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19];
}
So my next call would be:
makeCall(headers, 20, 40);
and so on so forth, until I got all 133 items from the array.
The question is...what is the cleanest way to continue to make subsequent calls until I've gotten and stored all 133 items from the array? Given that the count could be any number, it's hard to imagine how I can do this. I was thinking of nesting more ajax calls in a "success" function, but it's not scalable if I get back a number like 300.
Does anyone have any advice on how to proceed?
Thanks in advance!
EDIT:
So based on the advice in the comment, I've attemped to make the call recursive--but it doesn't seem to function as intended:
var theData = [];
var minCounter=0;
var maxCounter= minCounter + 20;
function makeCall(headers, min, max) {
$.ajax({
headers: headers,
url: "https://coolapi.com/data?begIndex" + min + "&endIndex=" + max + "&begTimestamp=1404198000000&endTimestamp=1409554800000",
type: "GET",
dataType: 'JSON',
success: function (data) {
theData.push(data.result);
newMin = minCounter + 20;
if (data.count >= theData.length ) {
makeCall(headers, newMin, maxCounter);
}
}
});
}
makeCall(headers, minCounter, maxCounter);
How do properly increment the variable as well as set the flag?
SECOND EDIT:
The method below works using the second comment's suggestion, but there are some issues here as well...
function doAjax(headers, min, dObject) {
var max = min + 20;
$.ajax({
headers: headers,
url: "https://coolapi.com/data?begIndex" + min + "&endIndex=" + max + "&begTimestamp=1404198000000&endTimestamp=1409554800000",
type: "GET",
dataType: 'JSON',
success: function (data) {
results.push(data);
window.count = data.count;
dObject.resolve();
}
});
}
// array that will contain all deferred objects
var deferreds = [];
// array that will contain all results
var results = [];
// make the ajax calls
for (var i = 20; i < 133 ; i+= 20) {
var dObject = new $.Deferred();
deferreds.push(dObject);
doAjax(headers, i, dObject);
}
// check if all ajax calls have finished
$.when.apply($, deferreds).done(function() {
console.log(results);
});
var dObject = new $.Deferred();
doAjax(headers,0, dObject);
First, the data doesn't push to the array in order. There doesn't seem anyway to fix this. Also strangely enough, in the for loop--I have to set the number for it to actually work. Trying to store it in a variable doesn't seem to work as well...Suggestions here?
Here's a working implementation based around the code you started with. Code is commented to help you understand what is happening:
// Change these constants to suit your purposes.
var API_URL = 'https://coolapi.com/data';
var HEADERS = {};
var API_RESULTS_PER_REQUEST = 20;
var MAX_API_CALLS = 20;
// Count API calls to trigger MAX_API_CALLS safety lock.
var apiCalls = 0;
// Function we'll call to get all our data (see bottom).
function collectApiData(begTimestamp, endTimestamp) {
var dataReady = jQuery.Deferred();
var params = {
'begTimestamp': begTimestamp,
'endTimestamp': endTimestamp
};
var datasetsCollected = requestDatasets(params);
jQuery.when(datasetsCollected).then(function(data) {
dataReady.resolve(data);
});
return dataReady;
}
// Makes individual AJAX call to API
function callApi(params, headers) {
var $request = jQuery.ajax({
url: API_URL,
headers: headers,
data: params,
type: 'GET',
dataType: 'JSON'
});
return $request;
}
// Recursive function that makes API calls until data is collected, there is an
// error, or MAX_API_CALLS limit is hit.
function requestDatasets(params, resultsReady, resultsFetched) {
resultsReady = ( resultsReady !== undefined ) ? resultsReady : jQuery.Deferred();
resultsFetched = ( resultsFetched !== undefined ) ? resultsFetched : [];
// Trigger safety to avoid API abuse
if ( apiCalls >= MAX_API_CALLS ) {
console.error('Exceeded max API calls:', MAX_API_CALLS);
resultsReady.resolve(resultsFetched);
}
// Set index data
params.begIndex = resultsFetched.length;
params.endIndex = resultsFetched.length + API_RESULTS_PER_REQUEST;
// Request dataset from API
var apiRequest = callApi(params, HEADERS);
apiCalls += 1;
// Callback once API request has completed and data is ready
jQuery.when(apiRequest).done(function(data) {
var apiResultCount = data.count;
resultsFetched = resultsFetched.concat(data.result);
console.debug('Fetched', resultsFetched.length, 'of', apiResultCount, 'API results');
if ( apiResultCount > resultsFetched.length ) {
console.debug('Making another API call');
requestDatasets(params, resultsReady, resultsFetched);
}
else {
console.debug('Results all fetched!');
resultsReady.resolve(resultsFetched);
}
});
jQuery.when(apiRequest).fail(function(data) {
console.error('API error: returning current results.');
resultsReady.resolve(resultsFetched);
});
return resultsReady;
}
// Run script
var dataReady = collectApiData('1404198000000', '1409554800000');
jQuery.when(dataReady).then(function(data) {
console.log(data);
});
Here's a working fiddle that mocks the API using httpbin.org:
http://jsfiddle.net/klenwell/mfhLxun2/

How can I stop an object method call before the ajax has completed

I have a the following java script object
function eventTypeObj() {
allEventTypes = [];
// When the object is created go and get all the event types that can be included in journey or clusters.
$.ajax({
url: "/ATOMWebService.svc/GetDisplayEventTypes",
dataType: "json",
success: function(result) {
allEventTypes = eval("(" + result.d + ")");
}
});
// Returns a list of all the event type IDS.
this.getEventTypeIds = function() {
var eventTypeIDs = [];
for (var i = 0; i < allEventTypes.length; i++) {
eventTypeIDs.push(allEventTypes[i].Id);
}
return eventTypeIDs;
};
}
I was wondering if there is a way stop some one calling the eventTypeObj.getEventTypeIds(); before the ajax call in the constructor has succeeded, and there is no data in the allEventTypes array?
Something like this would be way better (im not guaranteeing this is 100% working, but the concept is sound):
function eventTypeObj() {
this.allEventTypes = [];
this.hasLoadedEventTypes = false;
var loadEventTypes = function(cb) {
$.ajax({
url: "/ATOMWebService.svc/GetDisplayEventTypes",
dataType: "json",
success: function(result) {
this.allEventTypes = eval("(" + result.d + ")");
this.hasLoadedEventTypes = true;
cb();
}
});
};
this.getEventTypeIds = function(updateEventTypes, callback) {
var _getEventTypeIds = function() {
var eventTypeIDs = [];
for (var i = 0; i < this.allEventTypes.length; i++) {
eventTypeIDs.push(this.allEventTypes[i].Id);
}
return eventTypeIDs;
};
if (!this.hasLoadedEventTypes || updateEventTypes) {
loadEventTypes(function(){ callback(_getEventTypeIds()); });
}
else callback(_getEventTypeIds());
};
}
Example usage:
var eto = new eventTypeObj();
eto.getEventTypeIds(false, function(eventTypeIdArray) {
// do stuff with the id array
});
/*
somewhere later on you want to get an updated eventTypeId array
in case the event types have changed.
*/
eto.getEventTypeIds(true, function(eventTypeIdArray) {
// do stuff with the updated ids
});
var allowCall = false;
function eventTypeObj() {
allEventTypes = [];
// When the object is created go and get all the event types that can be included in journey or clusters.
$.ajax({
url: "/ATOMWebService.svc/GetDisplayEventTypes",
dataType: "json",
success: function(result) {
allEventTypes = eval("(" + result.d + ")");
allowCall = true;
}
});
// Returns a list of all the event type IDS.
this.getEventTypeIds = function() {
if(!allowCall) return; // or pop up a message
var eventTypeIDs = [];
for (var i = 0; i < allEventTypes.length; i++) {
eventTypeIDs.push(allEventTypes[i].Id);
}
return eventTypeIDs;
};
}
Or just check if allEventTypes is empty or not.
There is no way to prevent someone from calling it too soon. What would you want to have happen if they call it too soon?
It looks like your code now currently returns an empty array if allEventTypes hasn't yet been filled in. You can decide whether the empty array is the right result or if you should throw an exception when it's called too early to make it absolutely clear to the caller that the data is not yet available.
You could provide some helper code for people who need that information, but it might not yet be available. For example, you could allow them to register a callback that would get called from the success handler after the data had been filled in. You could allow them to query whether the data is available yet.
If you don't want the responsibility for the timing to be on the callers, then you cannot offer a synchronous way to get this information. Instead, you would only offer a callback mechanism for getting the data. If the data is ready, the callback would get called immediately. If the data is not ready, the callback would get called when the ajax function completes. In either case, the caller would have to process the data in the callback only and getEventTypeIds would not be a normal call to get the data like it is now, but rather a call to register a callback that would be called with the data when was ready. This would relieve the caller from having to know implementation details of when the data was ready, but would force them to use the asynchronous nature of the callback mechanism.
this.getEventTypeIds = function(callback) {
if (allEventTypes.length > 0) {
// data is ready call the callback with the data now
} else {
// store the callback to be called later from the success handler
}
}
You can check if the eventType array is empty, right?
if(allEventTypes.length == 0)
{
return;
}

Categories