Trying out async.js for nodejs

I have a problem with code below:

var async = require("async");

function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

function hello(no){
    console.log(no);
    async.forEach(no,function print_list(x, callback){
        console.log("I am task number : ", x);
        var sleep_time = Math.floor((Math.random()*10)+1);
        console.log(sleep_time);
        sleep(sleep_time*1000);
    },function(err){if (err){console.log(err);}});
}

list = [];
for (var a = 1000; a > 0;a--){
    list.push(a);
};
hello(list);

In my mind I'm expecting that each this code will not block each other, but I found out that is still treated as synchronous code.

Where did I do it wrong?

Node.js is single threaded and your sleep function is taking over the CPU.

Try using setTimeout instead to have a more realistic example on how this works.

function hello(no){
    console.log(no);
    async.forEach(no,function print_list(x, callback){
        console.log("I am task number : ", x);
        var sleep_time = Math.floor((Math.random()*10)+1);
        console.log(sleep_time);
        // use setTimeout
        setTimeout( function() {}, sleep_time*1000);
    },function(err){if (err){console.log(err);}});
}