I am quite new to Promises and am having a hard time using them in this code. I want to get data from my database table, encrypt it, and then update the table with the new data. I wrote the following methods to do this:
function getUpdatedEncryptedData(total_records_count, field_name, field_name_new, additional_key) {
var limit = 1000;
var iterations = Math.ceil(total_records_count / limit);
var promises = [];
for (let i = 0; i < 1; i++) {
var deferred = q.defer();
promises.push(deferred.promise);
dataForUpdate().then(function (result) {
encryptData(result, field_name, field_name_new, additional_key).then(function (result) {
deferred.resolve();
}).catch(function (err) {
console.log(err);
});
}).catch(function (err) {
console.log(err);
});
};
console.log(promises);
return q.all(promises);
}
I'm running the above method here:
function run() {
getTotalRecordsCount(params.db_table_name).then(function (result) {
var total_records_count = result.total;
return getUpdatedEncryptedData(total_records_count, params.field_name, params.field_name_new, params.additional_key).then(function () {
console.log('All data encrypted');
var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);
}).catch(function (err) {
console.log(err);
});
})
}
I want to know the final operation time. When I set only one iteration, everything works fine and I can see a message saying "All data encrypted". However, when I set two or more iterations, I don't see this message.
Am I doing something wrong with the loop that's preventing it from stopping? When I set two iterations, console.log
returns the following:
[ { state: 'pending' }, { state: 'pending' } ]
I can't understand why the then
callback isn't being called.