【问题标题】:For loop, then after each iteration, update result of "async/await" [closed]For循环,然后在每次迭代后,更新“async/await”的结果[关闭]
【发布时间】:2018-09-01 16:38:44
【问题描述】:

循环后,如何更新“await”块的结果?

前:

for (let i = 0; i < 5; i++){
       let thing = await ( foo => {
       return thing;     // thing returns 15.
    });

   for (let j = 0; i < thing; i++){
       //will loop 15 times the first time (out of 5 times because of outer loop)
       //want to change value of thing to 9, so the next time it loops 9 times
   }
}

在内循环之后,我期待流程返回到等待块并重新评估值或执行。但这似乎没有发生,因为返回值是'没有改变。

我希望 thing 第一次返回 15,然后循环 15 次。在外循环的下一次迭代中,我希望 thing 返回 9,因此内循环 9 次。

编辑:对不起大家这是正确的,问题来自代码的另一部分。感谢您的帮助!

【问题讨论】:

  • 当您在内部循环中将值重新分配给thing 时,您可能正在更新您的作用域thing(用let 声明),它将在每次外部迭代后重新创建。我假设您在外部范围中有一个 thing 变量,在代码开头等于 15,如果是这样,您将无法以这种方式更改它。
  • 你是await一个函数表达式。这是没有意义的。这是你的真实代码吗?

标签: javascript node.js loops asynchronous async-await


【解决方案1】:

你在这里定义一个函数:

await ( foo => {
   return thing;     // thing returns 15.
});

但您从未真正调用过该函数。你可以这样称呼它:

await ( foo => {
   return thing;     // thing returns 15.
})()

...但是真的很难理解为什么你创建一个函数只是为了返回一个值。

另外,在您的第二个 for 循环中,您定义了 j,然后比较并增加了 i。这很难解释,我认为这可能是一个错字。

【讨论】:

    【解决方案2】:

    你只是定义一个函数而不是调用它。而且j 循环看起来也很可疑

    let thing = await ( foo => {
      return thing;     // thing returns 15.
    })();
    

    我认为这就是你想要做的。虽然不完全确定

    let thingArr = [15,9]
    for (let i = 0; i < 5; i++){
    
       let thing = await ( foo => {
         return thingArr[i];     // thing returns 15.
       })();
    
       for (let j = 0; j < thing; j++){
           //will loop 15 times the first time (out of 5 times because of outer loop)
           //want to change value of thing to 9, so the next time it loops 9 times
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 2016-04-09
      • 2016-08-02
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      相关资源
      最近更新 更多