I am still not understanding how asyncronous code works or is created in NodeJS. See below code and output.
Code:
var async = require('simple-asyncify');
function calc(){
n1 = Math.round(Math.random() * (100 - 1) + 1);
n2 = Math.round(Math.random() * (100 - 1) + 1);
n3 = n1*n2;
// console.log(n3);
return n3;
}
function longRun(id)
{
console.log("start long run: "+ id);
for(i=0; i<100000000; i++){
calc();
}
console.log("end long run: " + id);
}
longRunAsync = async(longRun);
console.log("before");
longRunAsync(1, function(){});
longRunAsync(2, function(){});
longRunAsync(3, function(){});
console.log("after");
Output:
before
after
start long run: 1
end long run: 1
start long run: 2
end long run: 2
start long run: 3
end long run: 3
Without the line
longRunAsync = async(longRun);
And using the original function longRun vs longRunSync the output is :
before
start long run: 1
end long run: 1
start long run: 2
end long run: 2
start long run: 3
end long run: 3
after
So obviously something is running asynchronously but not the way I expected. It looks like it does all the synchronous code then swings back around and does the functions that are supposed to be asynchronous in a synchronous way.
Why is the output not like the below and how can I make it execute like this:
before
start long run: 1
start long run: 2
start long run: 3
after
end long run: 1
end long run: 2
end long run: 3
I think you get the idea, I want each call of longRunAsync to run well, asynchronously.