2

I am calling one helper method from another helper method using Promise to wait for the result. I have problem where JsonArray array is empty after pushing object from forEach. Did I miss something? Here's the code:

loadRecords : function(component, event, helper) {
        var action = component.get("c.getRecord");
        action.setParams({ 
            param : 'xyz',

        });
        action.setCallback(this, function(response) {
            var state = response.getState(); 
 
            if (state === "SUCCESS") {
            
                let responseJSON;
                try {
                    responseJSON = JSON.parse(response.getReturnValue());
                  
                }
                catch (err) {
                    
                }

                let name;
                let JsonArray=[];
                const that = this;
               
                responseJSON.forEach(key=> {
                    that.getClauses(component, event, helper,key.Name)
                    .then(function(result) {
                        JsonArray.push(result);

                    });
                });
                console.log('JsonArray '+JSON.stringify(JsonArray)); //got empty here

            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors && errors[0] && errors[0].message) {
                    
                }
            }

        });
        $A.enqueueAction(action);
    } 


    getClauses : function(component, event, helper, name) {
        
       return new Promise(
        $A.getCallback(function(resolve, reject) {
        var action = component.get("c.getClausesByName");
        action.setParams({ 
            name :name.trim()
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            
            //console.log('jsonResp '+JSON.stringify(response.getReturnValue()));
            
            if (state === "SUCCESS") {
                
                
                var jsonResp = JSON.parse(response.getReturnValue());
                
                let JSONData = new Object ();
                JSONData.Code=jsonResp.Code;
                JSONData.Name= jsonResp.Name;
                
                resolve(JSONData);
            }
            else if (state === "INCOMPLETE") {
            }
                else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
        });
        $A.enqueueAction(action);
            })
        );
    }

1 Answer 1

1

The console.log(JsonArray) is running before you push the element into the JsonArray. This occurs because getClauses returns a promise. As a result the order of execution is as follows:

  • getClauses is called for each item in the array and returns a pending promise.
  • console.log(JsonArray) is called
  • All of the pending promises are resolved (or rejected),

You can see an example of this here - https://jsfiddle.net/o51ryagj/3/

You can use the following code to ensure that all of the promises are resolved / rejected before running the console.log code.


responseJSON.forEach(key=> {
                    JsonArray.push(that.getClauses(component, event, helper,key.Name))
                });

Promise.all(JsonArray).then(function() { console.log(JsonArray) })

Promise.all will ensure that .then is not called until all of the promises in the json array have been resolved,

1
  • Thank you very Much Tyler for the concise explanation. It is working fine now. Commented Apr 21, 2022 at 13:43

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.