【问题标题】:I'm struggling with changing this loop as asynchronous nodejs [duplicate]我正在努力将此循环更改为异步nodejs [重复]
【发布时间】:2019-11-10 02:10:54
【问题描述】:
  • 在一个循环中 -
    1. 从mysql获取一些数据
    2. 将数据插入特定数组(在 i 的索引处)

但如您所知,'i' 的增长比我预期的要早得多。 我知道这是 nodejs 的同步/异步问题的问题。 我想把它改成同步函数,但它太混乱了,也许是我第一次......

...
dbconn.pool.getConnection(function (err, conn) {

...

    for (var i = 0; i < search_result.length; i++) {
        console.log("1, i here : "+i)
        conn.query(sql_getId_and_count, [search_result[i].address], function (err, result) {

              console.log("2.i here:" + i)
              if (err) console.error(err)
              else {
                   console.log("here : " + result[0].counter)
              }
        })
    }
})

【问题讨论】:

  • 实际上你不需要让它同步,这不是nodejs的意思,而是让它异步,我想你只想在查询中访问变量i,然后请改用let var.

标签: node.js loops promise async-await


【解决方案1】:

您可以使用 while 循环。 请注意,node.js 不会中断 while 循环。

您也可以使用 process.nextTick(),并在其中编写实现。 例如:process.nextTick(function() {})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    相关资源
    最近更新 更多