【问题标题】:Looping with Promises in JS returning only last result [duplicate]在 JS 中使用 Promises 循环仅返回最后一个结果 [重复]
【发布时间】:2020-10-30 21:07:07
【问题描述】:

如果 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>

【问题讨论】:

  • 为什么是.promise()?没必要这么做。

标签: javascript typescript loops promise counter


【解决方案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>

【讨论】:

    猜你喜欢
    • 2020-05-06
    • 2018-06-05
    • 1970-01-01
    • 2014-10-26
    • 2019-02-08
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多