Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally call async function in Node

I have the following example code - the first part can result in an async call or not - either way it should continue. I cannot put the rest of the code within the async callback since it needs to run when condition is false. So how to do this?

if(condition) {
    someAsyncRequest(function(error, result)) {
        //do something then continue
    }
}

 //do this next whether condition is true or not

I assume that putting the code to come after in a function might be the way to go and call that function within the async call above or on an else call if condition is false - but is there an alternative way that doesn't require me breaking it up in functions?

like image 214
cyberwombat Avatar asked Oct 27 '12 03:10

cyberwombat


People also ask

Can you use async await in node?

Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.

What is asynchronous function in node?

Asynchronous programming in Node. js. Asynchronous I/O is a form of input/output processing that permits other processing to continue before the transmission has finished.

Is node JS really asynchronous?

NodeJS is an asynchronous event-driven JavaScript runtime environment designed to build scalable network applications. Asynchronous here refers to all those functions in JavaScript that are processed in the background without blocking any other request.

What is difference between promises and async await in node JS?

1. Promise is an object representing intermediate state of operation which is guaranteed to complete its execution at some point in future. Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously. 2.


2 Answers

A library I've used in Node quite often is Async (https://github.com/caolan/async). Last I checked this also has support for the browser so you should be able to npm / concat / minify this in your distribution. If you're using this on server-side only you should consider https://github.com/continuationlabs/insync, which is a slightly improved version of Async, with some of the browser support removed.

One of the common patterns I use when using conditional async calls is populate an array with the functions I want to use in order and pass that to async.waterfall.

I've included an example below.

var tasks = [];

if (conditionOne) {
    tasks.push(functionOne);
}

if (conditionTwo) {
    tasks.push(functionTwo);
}

if (conditionThree) {
   tasks.push(functionThree);
}

async.waterfall(tasks, function (err, result) {
    // do something with the result.
    // if any functions in the task throws an error, this function is 
    // immediately called with err == <that error>
});

var functionOne = function(callback) {
    // do something
    // callback(null, some_result);
};

var functionTwo = function(previousResult, callback) {
    // do something with previous result if needed
    // callback(null, previousResult, some_result);
};

var functionThree = function(previousResult, callback) {
    // do something with previous result if needed
    // callback(null, some_result);
};

Of course you could use promises instead. In either case I like to avoid nesting callbacks by using async or promises.

Some of the things you can avoid by NOT using nested callbacks are variable collision, hoisting bugs, "marching" to the right > > > >, hard to read code, etc.

like image 154
ambrons Avatar answered Sep 19 '22 17:09

ambrons


Just declare some other function to be run whenever you need it :

var otherFunc = function() {
   //do this next whether condition is true or not
}

if(condition) {
    someAsyncRequest(function(error, result)) {
        //do something then continue

        otherFunc();
    }
} else {
    otherFunc();
}
like image 28
Yanick Rochon Avatar answered Sep 19 '22 17:09

Yanick Rochon