Access variable inside and outside a function in javascript?

1

I'm trying to update some questions on a page, traversing a _for with the number of steps equal to the total of questions, so in each passage inject a question via $ .post (), and wait for the return to only then continue the loop . I do not know if this is the best way to do it, but for this situation I have, two problems have arisen:

  • Find external variable within a function
  • Prevent loop flow until $. when complete
  • The code I'm using is below:

    function recalcularPesos(){
    
        //courseid=
        var id = ['1','2','3','4','5'];
        var passo = 0;
        for (p = 0; p < id.length; p++)
        {
            passo = passo+1;
            $.post("https://test.site.net/mod/quiz/edit_rest.php?class=resource&courseid="+id[p]).then(function()
                {
                    console.log( passo+"a questão foi modificada" );
                    if(passo = id.length){
                        console.log('passo: '+passo);
                        //Atualizar página após todas as atualizações
                        setTimeout(location.reload(), num*2000);
                    }
                }, function() {
                    alert( passo+"a questão NÃO modificada" );
                }
            );
        }   
    }
    
    recalcularPesos();
    

    The way I'm doing it, I need to refresh the page to show the updated values of the issues, but the page is being updated even before completing all the posts (if there are too many issues, worse). I also noticed that the step variable returns in the terminal at all iteration steps, the maximum value ( 5 in this case).

        
    asked by anonymous 05.10.2017 / 01:16

    1 answer

    2

    Update: Using for is not recommended because it is asynchronous , ie it will loop without waiting for the $.when to return.

    The location.reload() in setTimeout must be enclosed in quotation marks.

    You can revoke the recalcularPesos() function whenever the URL invoked in $.post sends a positive return by looping up to the limit of items in the id array:

    var id = ['1','2','3','4','5'];
    passo = 0;
    function recalcularPesos(){
        if(passo < id.length){
            $.post("https://test.site.net/mod/quiz/edit_rest.php?class=resource&courseid="+id[passo]).then(
            function(){
                console.log( id[passo]+" a questão foi modificada" );
                passo++;
                recalcularPesos();
            },
            function() {
                console.log( id[passo]+" a questão NÃO modificada" );
            });
        }else{
            // aqui termina o loop
            setTimeout("location.reload()",2000);
        }
    }
    
    recalcularPesos();
    
      

    Note that I put the Array out of the function (!) so it does not keep repeating.

        
    05.10.2017 / 02:50