0

I am using jQuery and javascript to call a function within another to get required data; however, the first function finishes before the second is started and returns its data. How do I stop the fist function until the second has returned its data?

My code is:

.done(function(responseJson1a){
    alert(JSON.stringify(responseJson1a));
    
    var newRows = "";
    for (var i = 0; i < responseJson1a.length; i++) {
        alert(responseJson1a[i].ppl_time);
        newRows += "<tr><td class='button'><button type='button' name='updatePDRow' class = 'buttonFront'><span class='glyphicon glyphicon-plus'></span></button></td>";
        newRows += "<td class='keyvalue'>"
        newRows += "<select class='form-control activityWidth activityClass pdValue' name='activityInput'>"; //Activity
        
        var activityName = responseJson1a[i].activity;
        activityOptionsUpdate = newActivity (activityType, activityName);//Function with another ajax call
        
        newRows += "<option value='' disabled selected>No Activity</option>" + activityOptionsUpdate + "</select></td>"//Needs data from function call
            
        newRows += "<td class='button'><button type='button' name='removePDRow' class = 'buttonFront'><span class='glyphicon glyphicon-minus'></span></button></td></tr>";
    }
    $('#updateProgramDetailTablebody').append(newRows);
})

I found the solution to be ".while" and amended my code to:

.done(function(responseJson1a){
    
    for (var i = 0; i < responseJson1a.length; i++) {
        
        $.when(newActivity(responseJson1a[i].activityType, responseJson1a[i].activityName, 
                responseJson1a[i].ppl_time, responseJson1a[i].awards, responseJson1a[i].leadAssist)
                ).then(function(data,textStatus,jqXHR){
        });
    }
})

And moved all the row creation and attachment into the function "newActivity".

As ".while" is not mentioned in the previous answer I do not see how this is a duplicate question.

Glyn
  • 1,933
  • 5
  • 37
  • 60
  • Can use `Promise.all` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – Abdelrhman Gemi Nov 07 '20 at 06:58
  • I am sorry, I have read the examples provided and I do not under stand how to fix this. It seems that I need to use Promise; however, I can not figure out how to implement it AND it is not supported by Explorer which excludes my program from a large number of users. Can anyone please explain how I can convert my example please? – Glyn Nov 07 '20 at 21:53
  • As ".while" is not mentioned in the previous answer I do not see how this is a duplicate question. – Glyn Nov 09 '20 at 22:35

0 Answers0