0

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.

IronFlare
  • 2,287
  • 2
  • 17
  • 27
Dima Savenkov
  • 37
  • 1
  • 5
  • Avoid the [deferred antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi May 26 '19 at 16:57
  • You'd need to use `const deferred` instead of `var deferred` to have you callback close over the right object. – Bergi May 26 '19 at 16:58

0 Answers0