【问题标题】:JavaScript / Save context of varaible inside async function [duplicate]JavaScript /在异步函数中保存变量的内容[重复]
【发布时间】:2016-08-22 16:20:03
【问题描述】:

我在 JavaScript 中有以下代码:

for (var i = 0; i< uuids.length; i++){
     var attr = uuids[i]
     var uuid = attr["uuid"];
     console.log("uuid is: " + uuid)
     multiClient.hget(var1, var2, function(err, res1){
          console.log("uuid INSIDE hget is: " + uuid)
      }
}

hget 是一种异步方法。下面是这个函数的打印结果:

"uuid is: 1"
"uuid is: 2"
"uuid INSIDE hget is: 2"
"uuid INSIDE hget is: 2"

我希望在 hget 函数中保存 uuid 的上下文,所以我会得到:

"uuid is: 1"
"uuid is: 2"
"uuid INSIDE hget is: 1" (where all the context before the loop has saved for this uuid)
"uuid INSIDE hget is: 2" (where all the context before the loop has saved for this uuid)

我该怎么做?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    以下代码

    multiClient.hget(var1, var2, function(err, res1){
       console.log("uuid INSIDE hget is: " + uuid)
    }
    

    uuid value 将是异步操作完成时的值。

    您可以通过执行匿名函数并将uuid 的值复制到其他变量(例如uuid_temp)来解决此问题,并使用该值,如下所示。

    (function() {
       var uuid_temp = uuid;
       multiClient.hget(var1, var2, function(err, res1){
          console.log("uuid INSIDE hget is: " + uuid_temp); //note uuid_temp here
       }
    }());
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多