IazertyuiopI
IazertyuiopI

Reputation: 488

convenient syntax for executing asynchronous functions if condition is met

Recently, I ended up doing something along those lines to achieve the execution of asynchronous functions (async_1,async_2,async_3 must be executed in that order.)

if(async_1_possible)
{
    async_1()
        .then(function(result_1){
            if(async_2_possible)
            {
                async_2()
                    .then(function(result_2){
                    sync(result_2);
                    async_3(result_1);
                    });
            }
            else
            {
                async_3(result_1);
            }
        });
}
else
{
    if(async_2_possible)
    {
        async_2()
            .then(function(result_2){
            sync(result_2);
            async_3();
            });
    }
    else
    {
        async_3();
    }
}

That code can quickly become quite ugly... I am looking for a syntax allowing me to do this :

if(async_1_possible){var queue += async_1};
if(async_2_possible){var queue += function(result_1){async_2();}};
if(async_3_possible){var queue += function(result_2){sync(result_2);async_3(result_1)}};

run queue();

edit : modified example to show passing promises result to the next one and also executing sync functions

edit 2 : looked at q library, but still fail to see a painless way to achieve the kind of process described above

Upvotes: 1

Views: 77

Answers (3)

IazertyuiopI
IazertyuiopI

Reputation: 488

Well this looks stupid, but is somewhat useful if you do not want to use a specific library for promises so I thought I'd post it here :

var promises_string = "$.when()";
    if(async_1_possible)  
    {promises_string+=".then(function(){return async_1();})";}

    if(async_2_possible)
    {promises_string+=".then(function(result_1){return async_2();})";}
    promises_string+=".then(function(result_2){sync(result_2);
    if(sync_3_possible){return async_3;}return $.when();})";}
    etc..

eval(promises_string);

In case when you need a result from an asynchronous call 2 steps or more before (like async_3(result_1), this fails, but I guess writing a parser would not be too hard...

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239473

If you are using Q then, you can do something like this

var funcs = [];
if (async_1_possible) {
    funcs.push(async_1);
}
if (async_2_possible) {
    funcs.push(async_2);
}
if (async_3_possible) {
    funcs.push(async_3);
}
funcs.reduce(Q.when, Q(initialVal));

Q Documentation entry for the same

Upvotes: 1

hyubs
hyubs

Reputation: 737

Kindly look at control flow libraries such as async and step. These help you organize your async callbacks and code complex flows that's hell in asynchronous coding (e.g. queuing, loops with async functions inside, etc.)

Upvotes: 1

Related Questions