Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS - Can't implement asynchronous function

NodeJS - Can't implement asynchronous function

Problem

I'm newbie in NodeJs. This is my code for learning Asynchronous Function.

//--------------------- MAIN ---------------
console.log("Endpoint 1\r\n");

testThread(1000000000,function (result){
    console.log(">>>>"+result+"\r\n");
});

console.log("Endpoint 2\r\n");

//------------------------------------------


function testThread(data,callback) {    
    //take a long time
    for(j=0;j

Run it:

node testthread.js

Always the result is:

Endpoint 1

>>>>4.335387639806787e+32

Endpoint 2

System prints "Endpoint 1", take 2 seconds, it prints ">>>>4.335387639806787e+32" after then it prints "Endpoint 2"

I'm not found the asynchronous here. It should be:

Endpoint 1

Endpoint 2

>>>>4.335387639806787e+32

Please explain me.

Problem courtesy of: Allan Vo

Solution

Asynchronous functions are functions that call other functions that are asynchronous. There is not other way to implement asynchronous functions in javascript/node.js. Which at first looks like a chicken and egg problem doesn't it? How can one write an asynchronous function if the requirement is that it must call another asynchronous function in order to be asynchronous?

The answer is that the lowest level asynchronous function must be implemented in C.

Fortunately, javascript/node.js has several built-in asynchronous functions implemented in C that we can use as building blocks in javascript to build our own asynchronous functions. Examples of such functions include the http.request() method, the socket.listen() method and probably the simplest setTimeout() and setInterval().

Here's an example of how one could rewrite your code to achieve asynchronous processing;

function long_task (repeat_number, callback) {
    // setTimeout is asynchronous, so keep calling it until we're done

    function loop () {
        if (repeat_number > 0) {
            repeat_number --;
            setTimeout(loop,1);
        }
        else {
            callback("I'm done!");
        }
    }

    loop();
}

console.log("calling long task");
long_task(10000,function(x){console.log(x)});
console.log("long task started");
Solution courtesy of: slebetman

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS - Can't implement asynchronous function

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×