My array always runs out of content

Asked

Viewed 36 times

0

I have a challenge when making ajax calls in Jquery.

I declared an array and after an ajax call I do to send a POST request, I want to take the id of the new object and store it in my array. Following the code.

 // Change view_1 to the view you want to listen to
$(document).on('knack-record-create.view_16', function(event, view, record) {


    var iterator = 0;
    var stagesIdToPopulate = [];

    stages = data.records; //console.log(stages);

    stages.forEach(function (stage) {

     var data1 = {field_88:stage.field_30, field_89:stage.id, field_90:stage.id, field_100:"5ba465ed83e85c2ffbda540f"};
  var processItemStagesURL = "https://api.knack.com/v1/objects/object_16/records";
        console.log(iterator);

       $.ajax({
                url:processItemStagesURL,
                type: 'POST',
                headers: headers,
                data: JSON.stringify(data1),
                }).done( function (response) {
                    //stagesIdToPopulate[iterator] = response.id;
                    stagesIdToPopulate.push(response.id);
                    //stagesIdToPopulate = a(stagesIdToPopulate,iterator,response);
                    console.log('Record Added! Its Id is: ' + stagesIdToPopulate);
                });

iterator++;

            }) // fim do foreach

 console.log('Este array nunca tem valor: ________' + stagesIdToPopulate);
});

Can anyone help me understand why my array after for never has sff content? Thanks in advance.

  • 5

    It is not "never", it is that you are trying to print the value before the server returns a response. This code is asynchronous. See What is the asynchrony?.

  • When I print on this console line.log('Record Added! Its Id is: ' + stagesIdToPopulate); already has content but in the last line it is not that I do not understand.

  • 3

    $.ajax({ is asynchronous. Hypothetically it may take 30 seconds or a minute to execute }).done( function (response) { stagesIdToPopulate.push(response.id); and meanwhile the console.log('Este array nunca tem valor: ________' + stagesIdToPopulate); has already been executed. Start by reading about asynchrony and understand how it works.

  • Thanks to everyone I’ve already looked at the links you sent and I managed to solve my challenge.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.