0

Following this link http://greenash.net.au/thoughts/2012/11/nodejs-itself-is-blocking-only-its-io-is-non-blocking/ I'm trying to code two non-blocking functions:

blocking code:

function LongBucle() {
    for (x=0;x<=10000;x++) {
        console.log(x);
    }
}

function ShortBucle() {
    for (x=0;x<=10;x++) {
        console.log("short "+x);
     }
}

LongBucle();
console.log("Long bucle end");

ShortBucle();
console.log("Short bucle end");

Now I try to turn the code into non blocking code so the "console.log("Short bucle end");" should be shown first?

function ShortBucle(callback) {
    for (x=0;x<=10;x++) {
        console.log("corto "+x);
    }
callback(x);
}


function LongBucle(callback) {
    for (x=0;x<=10000;x++) {
        console.log(x);
     }
     callback(x);
}


LongBucle(function(err) {
    console.log('Long bucle end');
});


ShortBucle(function(err) {
   console.log('short bucle end');
});

But it doesn't work. What am I doing wrong?

1
  • Calling callback is still blocking, use setImmediate Commented Nov 25, 2013 at 12:08

1 Answer 1

1

Adding a callback doesn't make your code asynchronous. As Javascript is a single-threaded language, only one instruction is executed at a given time. This means that this snippet will hang forever, no matter what you do:

function a() {
    while (true) {}
}

a();
console.log('Done.');

To process some amount of code later (ie. asynchronously), you can use process.nexTick() or setImmediate:

function LongBucle(callback) {
    setImmediate(function() {
        for (x=0;x<=10000;x++) {
            console.log(x);
         }
         callback(x);
    })
}

Here is an article explaining process.nextTick() and the event loop in Javascript.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you setImmediate worked but then I should accept this webpage example is wrong? greenash.net.au/thoughts/2012/11/…
Which example are you talking about?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.