0

I have a async function that breaks it's callbacks into an object success and error, this function takes one param (besides the callback) "pink".

async("pink",{
    success:function(){

    },
    error:function(){

    }
});

I want to make plural version of this function that takes in an array and returns the true or false value for the async action.

asyncs(["blue","red","green"],function(values){
    console.log(values); // [true,true,true];
});

The trick is that each acync action needs to be within the next, the value of the function (true or false) needs to be pushed() into a "global" (higher in scope) variable values and the returned in a master callback(values) at the end (when the count reaches the array length)

This is a very rudimentary way of nesting each async() function and returning the values, it is limited because it manually trails only 3 array values.

var asyncs = function(params,mstrCB){
    var length = params.length;
    var values = [];
    async(param[0],{
        success:function(){
            values.push(true);
            async(param[1],{
                success:function(){
                    values.push(true);
                    async(param[2],{
                        success:function(){
                            values.push(true);
                            mstrCB(values);
                        },
                        error:function(){
                            values.push(false);
                            mstrCB(values);
                        }
                    });
                },
                error:function(){
                    values.push(false);
                     mstrCB(values);
                }
            });
        },
        error:function(){
            values.push(false);
            mstrCB(values);
        }
    });
};  
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • if you are going to do this more often (and you are) i suggest you use this great little lib: https://github.com/willconant/flow-js – mkoryak Nov 29 '12 at 17:24

1 Answers1

1

Use a counter instead of manually nesting. Put the request in its own function, and up on each success, increment the counter and if it's less than length, make a new request.

When i === length, call the mstrCB().

var asyncs = function(params,mstrCB){
    var length = params.length;
    var values = [];
    var i = 0;

    if (length)
        makeRequest();

    function makeRequest() {
        async(params[i], {
            success:function(){
                values.push(true);

                 // Increment the counter
                i++;

                if (i === length)  // we're at the end
                    mstrCB(values);
                else
                    makeRequest(); // there's still more, so make another request
            },
            error:function(){
                values.push(false);
                mstrCB(values);
            }
        });
    }
};
I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77