Pensierinmusica
Pensierinmusica

Reputation: 6940

NodeJS sequential async with conditional statements

Is it possible to write NodeJS code that executes several async steps in a sequential way, where some steps get executed or bypassed based on conditional statements?

Let me try to write an example in pseudo code.

Imagine you have something like

step1.then(step2).then(step3);

Now let's add an option:

var opt = true;

How is it possible to achieve something like:

step1.then(opt && step2).then(step3);

Or, if we had let's say 2 different possible steps in the middle:

step1.then(opt ? step2 : step3).then(step4);

EDIT

If the optional step was at the beginning instead?

(opt && step1).then(step2).then(step3);

It would be awesome if anyone could shed some light or come up with proposals!

Thanks

Upvotes: 2

Views: 1138

Answers (1)

t.niese
t.niese

Reputation: 40842

Assuming step2 and step3 are functions returning a promise what is the problem with:

 step1.then(function() {
     if( opt ) {
         return step2();
     } else {
         return step3();
     }
 })
 .then(step4);

EDIT

Your first example step1.then(opt && step2).then(step3); would look like this:

step1.then(function() {
     if( opt ) {
         return step2();
     }
 })
 .then(step3);

If you don't return anything then undefined is returned. For every returned value that is not a Promise, the library will create a Promise that is resolved with that value.

Promises/A+: The then Method:

promise2 = promise1.then(onFulfilled, onRejected);

If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x).

Upvotes: 2

Related Questions