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

Trouble with keeping Node.js asynchronous

Trouble with keeping Node.js asynchronous

Problem

So, I ran into a situation today in which I needed to place an Asynchronous database call into a custom Function of mine. For example:

function customfunction(){
    //asynchronous DB call
}

Which I then call from another point in my program. First off, just to be on the safe side, is this still asynchronous? (I'll operate under the assumption that it is for the continuation of my question). What I would like to do from here is call another specific function on completion of the async DB call. I know that the DB call will trigger a callback function on completion, but the problem is that this customfunction is very generic (meaning it will be called from many different point in my code), so I cannot put a specific method call in the callback function since it won't fit all situations. In case it isn't clear what I'm saying, I will provide an example below of what I would LIKE to do:

//program start point//
customfunction();
specificfunctioncall(); //I want this to be called DIRECTLY after the DB call finishes (which I know is not the case with this current setup)
}

function customfunction(){
    asynchronousDBcall(function(err,body){
    //I can't put specificfunctioncall() here because this is a general function
    });
}

How can I make the situation above work?

Thanks.

Problem courtesy of: Ari

Solution

This is how you do it:

//program start point//
customfunction(specificfunctioncall);

and in customfunction():

function customfunction(callback){
    asynchronousDBcall(function(err,body){
        callback();
    });
}

Functions are just data that you can pass around just like strings and numbers. In fact, with the anonymous function wrapper function(){...} you can treat CODE as just data that can be passed around.

So if you want some code to execute on the completion of the DB call instead of a function just do this:

customfunction(function(){
    /* some code
     * you want to
     * execute
     */
});
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

Trouble with keeping Node.js asynchronous

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×