用JS中的Promises循环仅返回最后一个结果

时间:2020-07-10 07:03:44

标签: javascript typescript loops promise counter

如果Promise在for循环内并且在then构造函数中,我们要打印当前计数器,它将5次打印出最后一个计数器值。 应该怎么做才能打印从0到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>

1 个答案:

答案 0 :(得分:1)

解决方案正在使用let关键字而不是var。主要区别是范围的区别,而let仅在声明的范围内可用,例如在for循环中,var可以在循环外部访问。

<!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>

相关问题