【问题标题】:Node.js not executing nested for loop correctly as it is asynchronousNode.js 没有正确执行嵌套的 for 循环,因为它是异步的
【发布时间】:2020-06-01 10:04:40
【问题描述】:
let data = {};
sql.query("SELECT * FROM courses WHERE name = ?", [name], function(err, course) {
  if (err) result(null, err);
  else {
    data.id = course[0].id;
    data.course = course[0].name;
    data.terms = []

    sql.query("SELECT * FROM terms WHERE course_id = ?", [course[0].id], function(err, term) {
      if (err) result(null, err);
      else {
        for (let i = 0; i < term.length; i++) {
          data.terms.push({
            id: term[i].id,
            name: term[i].name,
            modules: []
          });
          sql.query("SELECT * FROM modules WHERE term_id = ?", [term[i].id], function(err, module) {
            if (err) result(null, err);
            else {
              for (let j = 0; j < module.length; j++) {
                data.terms[i].modules.push({
                  id: module[j].id,
                  name: module[j].name,
                  topics: []
                });
                sql.query("SELECT * FROM topics WHERE module_id = ?", [module[j].id], function(err, topic) {
                  if (err) result(null, err);
                  else {
                    for (let k = 0; k < topic.length; k++) {
                      data.terms[i].modules[j].topics.push({
                        id: topic[k].id,
                        name: topic[k].name
                      });
                    }
                    if (i === term.length - 1) result(null, data);
                  }
                });
              }
            }
          });
        }
      }
    });
  }
});

【问题讨论】:

  • 知道箭头函数,用(//arguments ) =&gt; { //function body }替换所有函数,即function (){}
  • 我已经这样做了,但什么也没发生。
  • 很遗憾地告诉你,这是一个经典的“回调地狱”例子,所有的异步操作都应该转换成 Promise,然后整个事情可以用 Promise 写得更干净,.then()/.catch()async/await。但是,第一步是将所有异步操作转换为使用 Promise,然后您可以使用 Promise 控制流来管理异步流。仅供参考,有一个不同版本的 mysql 内置了承诺支持。
  • 你能这样写吗,因为当我试图这样做时,我在索引时感到困惑。如您所见,我在插入数据时使用了特定的数组位置。
  • 关于 for 循环内的异步 node.js 函数有很多 Stack Overflow 问题。您研究并尝试了其中的哪些,为什么它们没有解决您的特定问题?

标签: node.js


【解决方案1】:

我建议你使用 Bluebird 包。这里是npm页面的链接https://www.npmjs.com/package/bluebird你之前试过吗?

你也可以在这里查看官方文档页面http://bluebirdjs.com/docs/getting-started.html

这是我最近从事的某个项目的一个 sn-p。我将它粘贴在这里作为示例。

在 while 循环中,Bluebird 遍历一组玩家并等待(一秒钟),然后再移动到下一个数组项:

别忘了先导入bluebird:const Promise = require('bluebird');

while(someCondition) {
  await Promise.each(players, async (p) => {
    const team = this.getTeamByPlayer(p);
    logger.info(`[${team.name}] ${p.nombre} is making a move`);
    p.jugar();
    await this.wait(1000);
  })
 }

this.wait(n)是一个实现异步超时的类方法

如您所见,我在迭代和循环内部都使用了 async/await。

Bluebird 还有一个Promisify 方法,可以帮助您以“async/await”的方式编写代码,使您的代码最清晰!

如果您有任何问题,请告诉我!

希望对你有帮助!

卢卡斯-

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-05
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2015-04-11
    • 1970-01-01
    相关资源
    最近更新 更多