I have the following function which is called by another function:
function fetchAllRecords(client, item, region, offset, savedCount, totalCount) {
offset = offset || 1;
savedCount = savedCount || 0;
totalCount = totalCount || 0;
return processQueue(client, item, offset, region).then(function (result) {
return associate(result, item, region)
}).then(function (success) {
return saveBatch(item, success.allResources, region);
}).then(function (result) {
savedCount += result.savedCount;
totalCount += result.totalCount;
if (debugmode) {
console.log(savedCount + '/' + totalCount);
}
offset += item.limit;
return fetchAllRecords(client, item, region, offset, savedCount, totalCount);
}).catch(function (err) {
if (err == 'done')
return 'done';
// All of the above steps have built-in retry so we assume there's a non-recoverable error in this batch and move to next
if (err.message === 'LIMIT_EXCEEDED') {
offset += item.limit;
return fetchAllRecords(client, item, region, offset, savedCount, totalCount);
}
else {
******************* Problem Line ********************
console.log('Miscellenious error in fetachAllRecords, moving to next resource');
console.log(JSON.stringify(err));
throw new Error('Misc');
}
});
}
and it is being called like this in the other function
function processResource(client, item, debugmode, region) {
var deferred = q.defer();
if (item.resource === "Property" && region === "ccmls") {
var cities = cities.list;
item.query = item.query + ' ,(City=|' + cities.join() + ')';
}
fetchAllRecords(client, item, region)
.then(function (result) {
if (debugmode) {
console.log('fetchAllRecords: ' + item.resource + '.' + item.class + ' completed...');
}
deferred.resolve(result);
})
.catch(function (err) {
console.log(item.resource + '.' + item.class + ' failed with error: ' + JSON.stringify(err));
deferred.reject(err);
});
return deferred.promise;
}
In the above problem line, it is supposed to reject fetchAllRecords
and in processResource
the fetachAllResources
catch
handler should be called, but for some weird reason, the problem line keeps being called after throw and after getting called a dozen times(at random) it finally rejects the promise returned by fetchAllResources
in processResource
.
Am I missing something obvious here? Also please comment on my style of using promises, is it alright or I need more practice?