简体   繁体   中英

How to make this recursive code execute synchronously in node.js

I have a recursive function that execute synchronously in javascript and gives me the result that i desired. But when i was executing the same code in node.js the result of the function is delivered even before the function got executed completely. can someone help me execute the code synchronously in node.js?

I have tried with callbacks also. But I could see finals got returned even before the inner recursive functions got executed.

Can someone help me get this code work synchronously in node js?

var finals = [];

function algo(parentApi)
{
    var i, j, k = 0;
    var parents = [];
    for (j = 0; j < parentApi.length; j++)
    {
        for (i = 0; i < childProjectApiList.length; i++)
        {

            if (parentApi[j].api_tag == childProjectApiList[i].dependent_api)
            {
                parents[k++] = childProjectApiList[i];
            }
        }
        if (parents.length > 0)
        {
            async.map(parents, projectComponent.getApiResult,
                function(err, result)
                {
                    finals = finals.concat(result);
                    algo(parents);
                });

        }
    }
    if (j == parentApi.length)
    {
        return finals;
    }
}

i expect the function to return finals after whole recursive process is completed but it returns me empty array.

Try this,

var finals = [];

function algo(parentApi){ var i, j, k = 0, parents = [];

for (j = 0; j < parentApi.length; j++) {
    for (i = 0; i < childProjectApiList.length; i++) {
        if (parentApi[j].api_tag == childProjectApiList[i].dependent_api){
            parents[k++] = childProjectApiList[i];
        }
    }

    if (parents.length > 0){
        async.map(parents, projectComponent.getApiResult, function(err, result) {
            finals = finals.concat(result);
            algo(parents);
        });
    }else if (j == parentApi.length) {
        return finals;
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM