-1

If promise is inside for loop and in function located in then construct we want to print out current counter, it will 5-times print out last counter value. What should be done to print sequence from 0 to 4?

 <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>Demo</title>
    </head>
    <body>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    
    <table style="width:100%">
        <tr>
            <th>test</th>
        </tr>
    </table> 
    
    <script>
    
    var $row = $('tr')
    for (var k = 0; k < 5; k++) {
     $("<tr><th>test</th></tr>").insertAfter($row).promise().then(() => print(k));
    }
    
    function print(counter){
        setTimeout(() => console.log(counter), 1000);
    }
    
    </script>
      
    </body>
    </html>
Bruno B
  • 199
  • 1
  • 5

1 Answers1

1

Solution was in usage of let keyword instead of var. The main difference is the scope difference, while let can be only available inside the scope it's declared, like in for loop, var can be accessed outside the loop for example.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Demo</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

<table style="width:100%">
    <tr>
        <th>test</th>
    </tr>
</table> 

<script>

let $row = $('tr')
for (let k = 0; k < 5; k++) {
 $("<tr><th>test</th></tr>").insertAfter($row).promise().then(() => print(k));
}

function print(counter){
    setTimeout(() => console.log(counter), 1000);
}

</script>

</body>
</html>
Bruno B
  • 199
  • 1
  • 5