Share via


Nested For Loop with Async Calls

Recently I came across situation where I need to form a 2D array inside an 2D Array getting data from two SharePoint list.

I did it with below code.

async function  GetTotalArrayByEventID(parent_id)
{
    var totalArray = [];
    await $pnp.sp.web.lists.getByTitle("ParentList").items.filter("ParentId eq "+ parent_id +"").get().then(async function(result){
        if(result.length > 0)
        {
            var arrActivity = [];
            for(var k = 0; k < result.length; k++)
            {
                var currResultItm = result[k];
                var arrItem = [];
                var childID = currResultItm["ID"];
                arrItem.push(currResultItm["ID"]);
                arrItem.push(currResultItm["Title"]);
                             
                 
                    await $pnp.sp.web.lists.getByTitle("ChildList").items.filter("ParentLookupId eq "+ Parent_id + "and ChildLookupId eq " + childID +"").get().then(function(result_child){
                    if(result_child.length > 0)
                    {
                        var arrBudget = [];
                        for(var j = 0; j < result.length; j++)
                        {
                            var arrBudgetItem = [];
                            var Curr_result_budget_item = result_child[j];  
                            arrBudgetItem.push(Curr_result_budget_item["Title"]);
                            arrBudgetItem.push(Curr_result_budget_item["Child_Amount"]);                            
                            arrBudget.push(arrBudgetItem);
                        }
                        arrItem.push(arrBudget);
                    }
                });
                arrActivity.push(arrItem);
            }// ********** OUTER FOR LOOP ENDS          
            totalArray.push(arrActivity);
        }
    });
    return totalArray;

Hope this will help others as well me in many projects...