0

I have this bit of code with node.js.

I want to make 2 parallel task and I don't care in what order they finish. In the end both will insert something in a database, but I must do some calculations and some string replacement first.

Is it normal that my test function always finish first when I run this bit ?

I execute the code 10-20 times and test always finish before test2.

async.parallel([
function (callback) {
    v2 = test(200);
    callback(null, v2);
},
function (callback) {
    v3 = test2(300);
    callback(null, v3);
}
], function (err, results) {
    console.log(results)
});

My test function here will have like 2-3 nested for loops, will count a lot of information in memory.

function test(a) {
    for (var i = 0; i < 1000000; i++) {
        a = a + 1;
    }
    console.log('Finished 1');
    return a + 100;

}

This function should finish first because there is only one operations in it...

function test2(a) {

    console.log('Finished 2');
    return a + 200;

}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
metraon
  • 1,229
  • 2
  • 11
  • 26
  • How are you testing that it finishes first? If it's just that it's the first element in the array, that's because async preserves output order to the order of the functions. – Zoey Mertes Oct 13 '14 at 23:36

1 Answers1

2

These are not actual asynchronous functions. They run synchronously so the async library cannot run them concurrently. It will just run them in the order you passed them.

Thinking that you're passing it actual asynchronous functions, the async library will start the first operation by calling the first function you pass, but you do all your work in that start operation and even call the completion callback. So, before it even has time to start the second operation, your first operation is already done.

Remember, the async library does not make things asynchronous that are not actual asynchronous operations. It just helps you manage and sequence operations some of which may be actual asynchronous operations.

jfriend00
  • 683,504
  • 96
  • 985
  • 979