【问题标题】:How to get loop value [duplicate]如何获得循环值[重复]
【发布时间】:2019-09-09 17:15:23
【问题描述】:

如何在循环之外获取循环值。 我解释我的问题:

我有一个循环。在这个循环中,我提出了几个请求。我希望每个请求都检索变量的值,然后在循环结束时显示所有内容。

这是我的代码示例:

var log = [];
for (var i = 0; i < result.length; i++){
  validateExcelJson(result[i], function(id) {
    if(result[i].EMAIL != "") {
      var query = "SELECT id as ID from Table_users where DELETED = 0 and LOWER(AES_DECRYPT(EMAIL, '"+cryptoKey+"')) = LOWER('" + result[i].EMAIL + "');";

      var data = result[i];

      store.action = "excel Valid";
      log.push(store)
      console.log("test")

      connection.query(query, function (error, results1, fields) {
        console.log("test 1")
        if (error) throw error;

        if (results1.length > 0)
        {
          store.state = "update user";
          log.push(store)
        }
        // user create
        else
        {
          store.state = "create user";
          log.push(store)
        }
      });
    }
  });

}
console.log(log)

这是我得到的:

test
test
test
test
[ { action: 'excel Valid' },
  { action: 'excel Valid' },
  { action: 'excel Valid' },
  { action: 'excel Valid' },
  { action: 'excel Valid' } ]
test 1
test 1

很遗憾我没有存储值(store.state = "create user" / store.state = "update user")。 我想得到的是:

[ { action: 'excel Valid', state: 'update user' },
  { action: 'excel Valid', state: 'update user' },
  { action: 'excel Valid', state: 'create user' },
  { action: 'excel Valid', state: 'create user' },
  { action: 'excel Valid', state: 'create user' } ]

我该怎么办?我认为这与异步方法有关。如果是这样,如何使同步? (承诺?我承认这对我来说非常模糊)

【问题讨论】:

  • 这篇 SO 帖子可能会有所帮助 (stackoverflow.com/questions/31775177/…)
  • console.log 在调用 query 中的回调之前运行,这就是您没有结果的原因。
  • 你可以把最后一个console.log(log);放在一个单独的函数中,当日志完全填满时调用这个函数。假设单独的函数叫做doConsoleLog(),那么在connectionQuery的回调函数的最后,可以写if (log.length == result.length*2) doConsoleLog();

标签: javascript node.js loops


【解决方案1】:

首先,您似乎将数组填充了两次

store.action = "excel Valid"; 
log.push(store)

稍后在您的查询回调中

if (results1.length > 0)
{
 store.state = "update user";
 log.push(store)
}
// user create
else
{
 store.state = "create user";
 log.push(store)
}

据此,您应该有一个这样的 var 日志:

[ { action: 'excel Valid' },
  { action: 'excel Valid' },
  { action: 'excel Valid' },
  { action: 'excel Valid' },
  { action: 'excel Valid' } 
  { action: 'update user' } 
  { action: 'update user' } 
  { action: 'create user' } 
  { action: 'create user' } 
  { action: 'create user' } ]

但是没有,所以它让我觉得回调没有启动或没有返回预期的格式或值,所以我们可以看到查询响应吗?

【讨论】:

  • 我认为你是对的,他填充了两次数组,但最后的 console.log(log) 在回调之外,因此将在回调之前执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2021-06-04
相关资源
最近更新 更多