【问题标题】:Why does my async.waterfall javascript sequential code not end?为什么我的 async.waterfall javascript 顺序代码没有结束?
【发布时间】:2016-12-31 03:44:35
【问题描述】:

当我运行以下代码时,它顺序连接到 MongoDB,然后关闭,使用 javascript 中的 async.waterfall,程序没有按预期结束。相反,它似乎只是在“数据库关闭”行之后等待。

$ node test-async2.js
hit connectMongo
Connected correctly to server, DB: notes
hit closeMongo
DB closed

[program just waits here, doesn't end]

我期待节目结束。我犯了什么错误?

const
  async = require('async'),
  MongoClient = require('mongodb').MongoClient,
  url = 'mongodb://localhost:27017/notes';    

function connectMongo(next) {
  console.log('hit connectMongo');
  MongoClient.connect(url, function(err, db) {
    console.log("Connected to server, DB: " + db.databaseName);
    next(null, db);
  });
}

function closeMongo(db, next) {
  console.log('hit closeMongo');
  db.close;
  next(null, "DB closed");
}

// perform connect then close sequentially
async.waterfall([
  connectMongo,
  closeMongo,
], function (err, result) {
    if (err) throw err;
    console.log(result);
});

【问题讨论】:

  • the program to end. 是什么意思?曾经写在代码中的东西,就是正在发生的事情。我认为` ctrl+c` 将帮助您停止程序。我认为它不会自动结束。
  • 你在打电话给close吗?没有括号。
  • @cartant - 就是这样,非常感谢。我一直盯着代码看太久了,我只是看不出一个愚蠢的错误。再次感谢!!!

标签: javascript node.js mongodb asynchronous


【解决方案1】:

尝试使用 db.close() 代替 db.close

另外,添加一个回调到 db.close 以在关闭时检查错误。

【讨论】:

  • 非常感谢@Tom,我看不到摆在我面前的愚蠢错误。关于关闭时检查错误的好点 - 再次感谢。
猜你喜欢
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 2018-08-16
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
相关资源
最近更新 更多