Link to home
Start Free TrialLog in
Avatar of kevbob650
kevbob650Flag for United States of America

asked on

Node JS Async Function Call Problem

I've attached a text file with a code snippet to keep this simple.  Issue is I have two function that gather data from different sources and I want to append a main array with the values from the functions.  Problem is they run async so not all values are being added, only some from each function call. I need them to run in series (or get the callback working as needed) so that all of the values from each function are appended to the main array.  Thanks in advance...
Async-Function-Call.txt
Avatar of Rob
Rob
Flag of Australia image

There will be a more elegant solution, however this will do the job:

getFirstData(dividedArray[i].toString(), function(res) {
            console.log("getting aqe data");
            for ( var a=0; a<arrMain.length; a++ ) {
                for ( var key in res[0]) {
                    if(key == arrMain[a][1]) {
                        arrMain[a].push(res[0][key]['TeamName']);
                        arrMain[a].push(res[0][key]['TeamID']);
                    }
                }
            }     						                                   
        
        getSecondData(dividedArray[i].toString(), function(res) {
            for(var k=0; k<arrMain.length; k++) {
                for(var j=0; j<response.length; j++) { 
                    if(response[j]['keyValue'] == arrMain[k][1]) {  // find like tickets, pull needed data elements and push to CBUS data array from above
                        arrMain[k].push(response[j]['Group']);
                        arrMain[k].push(response[j]['Organizatioin']);
                        arrMain[k].push(response[j]['Location']);								  
                    }
                }
            }
        });
});

Open in new window

Where is your getFirstData function defined?  You can force synchronous if you need to but I can't direct you without knowing what it's calling
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is where you should be using promises. You do not want the "pyramid of doom", ie. long sequences of callbacks. First of all, you loose the advantage of asynch, second your code will become entangled and hard to maintain.

the Q library for node makes promises easy:
https://github.com/kriskowal/q

specifically, look at Q.all
Avatar of kevbob650

ASKER

That got me where I was going.  I should have shared the functions I was calling but it got too complex.  I had to pass another variable in one of the callbacks, and use it instead of the "divided array".  Funny stuff async!  My code actually looks more sequential now, but it's using variables from the callback. So all is good.  I'm done with Node for a while. Off to Perl land now.  thanks again.