Question

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.

Was it helpful?

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
     */
});

OTHER TIPS

Jay, If asyncDbCall is a database library function, then it will have callback function as one of its parameter(if it is a real async function). Pass specificFunctionCall as a parameter to that function and you are done.

function CustomFunction{
  asyncDbCall(.....,specificFunctionCall);
}

Now on calling CustomFunction, it will call the asyncDbCall function and once it is completed, the asyncDbCall will automatically call your callback function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top