Search code examples
javascriptnode.jsdatabasesqlitenode-sqlite3

Data changing before it's used in function


I have been trying to send an email for each expired ticket in the database. Snip of it looks like this:

for (var i = 0; I < rows.length; ++i) {
    if (today > new Date(rows[i].end_date)) {
        (function(id) {
            db.exec('update tickets ' +
                    'set status="expired" ' +
                    'where ticket_id= ' + id + ';' +
                    'insert into changes ' +
                    'values(' + id + ',' +
                        '"system",' +
                        '"ticket expired",' +
                        '"' + (today.getUTCMonth() + 1) +
                        '/' + today.getUTCDate() +
                        '/' + today.getUTCFullYear() +
                    '");',
                    function(err) {
                        if (err) {
                            console.log(err);
                            return;
                        }

                        console.log(id);
                        sendAlert(id);
                    }
            );
        })(rows[i].ticket_id);
    }
}

As you can see I tried to use an anonymous function to keep the data in each call from changing but it still didn't work.

I don't know if I am missing something.


Solution

  • Seems the execution of this task is asynchronous. When you need to iterate over asynchronous calls, the operation sequence is not guaranteed.

    Maybe you need some control flow library such Async or Promise. There has some methods to control these flows even in iterations.