I currently have an application that depends on all data being retrieved then proceed with further code.
There is a primary function "_update()" that contains a loop, this loop calls _getData(). I need "_update()" to set a variable to true when all data has been received.
Here is what I have:
DataCollection.prototype._update = function () {
var _self = this;
var _itemsResponded = 0;
var itemData = [];
if (_self._ready) {
_self._ready = false;
this.collection.forEach(function (item, index) {
_self.apiData.id = item.id;
var ajaxPromise = _self._getData();
ajaxPromise.done(function(data){
itemData[index] = data;
_self._itemsResponded++;
});
})
if (_self._itemsResponded === _self.collection.length) {
_self._ready = true;
console.log(itemData);
console.log('done');
}
}
}
DataCollection.prototype._getData = function () {
var _self = this;
var ajaxPromise = $.ajax({
url: 'ajax.php',
data : _self.apiData,
dataType: 'json'
});
var dff = $.Deferred();
ajaxPromise.then(function(data) {
dff.resolve(data);
}, function(){
dff.reject();
});
return dff.promise();
}
From my understanding, the _getData function is working correctly. It's the .forEach in _update that does not work as expected. I thought .forEach was synchronous?