user3467433
user3467433

Reputation: 385

Node js for loop timer

I'm trying to test which Database, which can implemented in Node.js has the fastest time in certain tasks.

I'm working with a few DBs here, and every time I try to time a for loop, the timer quickly ends, but the task wasn't actually finished. Here is the code:

console.time("Postgre_write");

    for(var i = 0; i < limit; i++){
    var worker = {          
        id: "worker" + i.toString(),
        ps: Math.random(),
        com_id: Math.random(),
        status: (i % 3).toString()
    }
    client.query("INSERT INTO test(worker, password, com_id, status) values($1, $2, $3, $4)", [worker.id, worker.ps, worker.com_id, worker.status]);
}

console.timeEnd("Postgre_write");

when I tried like a few hundred I thought the results were true. But when I test higher numbers like 100,000, the console outputs 500ms, but when I check the PGadmin app, the inserts were still processing.

Obviously I got something wrong here, but I don't know what. I rely heavily on the timer data and I need to find a way to time these operations correctly. Help?

Upvotes: 0

Views: 630

Answers (1)

jluckin
jluckin

Reputation: 662

Node.js is asynchronous. This means that your code will not necessarily execute in the order that you have written it.

Take a look at this article http://www.i-programmer.info/programming/theory/6040-what-is-asynchronous-programming.html which offers a pretty decent explanation of asynchronous programming.

In your code, your query is sent to the database and begins to execute. Since Node is asynchronous, it does not wait for that line to finish executing, but instead goes to the next line (which stops your timer).

When your query is finished running, a callback will occur and notify Node that the query has finished. If you specify a callback function it will be run at that point. Think of event-driven programming, which the query's completion being an event.

To solve your problem, stop the timer in the callback function of the query.

Upvotes: 2

Related Questions