nodejs异步库:为什么在发生错误后没有触发回调?

kx1ctssn  于 2021-06-15  发布在  Mysql
关注(0)|答案(0)|浏览(298)

我一直在开发nodejs服务器的后端,该服务器目前使用库async和mysql。注意,这三个例程是在async的“瀑布”函数中执行的。其工作原理如下:
服务器连接到mysql数据库
mysql数据库在表“tag”中插入一个新条目
如果服务器试图插入一个重复的文件,则会抛出一个错误,测试将失败
服务器与mysql数据库断开连接
不幸的是,我用mocha运行的每个测试都会通过,即使服务器的mysql客户端试图插入一个副本。
我已经阅读了“async”库的文档。它说,如果在执行“瀑布”函数期间发生错误,控制流将被重定向到“瀑布”回调。我还试着查阅“mysql”库的文档。但我找不到任何能帮我解决问题的东西。我应该将可能引发错误的代码放在try-catch块中还是必须发出特殊回调?
文件:sqltagstest.js

var mysql = require('mysql');
var mySqlUtils = require('../../backend/MySqlHandler/MySqlUtils.js');
var mySqlTags = require('../../backend/MySqlHandler/MySqlTags.js');

describe('Create new tag',function(){
    var connection = "";
    var queryParams = "";
    before(function(done){
        connection = mysql.createConnection({
            host:'myHost',
            user:'root',
            password:'myPassword',
            database:'myDb'
        });
        queryParams = {
            name: 'Tag',
            description: 'Description',
            parent: 'root',
            creator: 'me',
            admin: false
        };
        done();
    });
    it('should create a new tag inside the database',function(){
        mySqlTags.CreateTag(connection,queryParams);
});

文件:mysqltags.js

var sqlUtils = require('./MySqlUtils.js');
var reflectChanges = require('./MySqlReflection.js');
var async = require('async');

function CreateTag(connection,queryParams){
  async.waterfall([
    function SetupData(callback){
      callback(null,connection,queryParams);
    },
    sqlUtils.ConnectToDatabase,
    sqlUtils.InsertTagIntoDatabase,
    sqlUtils.CloseDatabaseConnection
  ],function(err,results){
      if(err)
      {
          throw err;
      }
  });
}

function DeleteTag(connection,queryParams,serverResponse){
  async.waterfall([
    function setupData(callback){
      callback(null,connection,queryParams);
    },
    sqlUtils.ConnectToDatabase,
    reflectChanges.DeleteTagEntry,
    reflectChanges.GenerateUncategorizedTag,
    reflectChanges.UpdateChildrensParent,
    sqlUtils.CloseDatabaseConnection
  ],function(error,results){
    if(error){
      serverResponse(queryParams,error,false);
    }else{
      serverResponse(queryParams.name,true);
    }
  });
}

function EditTag(queryParams,serverResponse){
  async.waterfall([
    sqlUtils.ConnectToDatabase,
    sqlUtils.CloseDatabaseConnection
  ],function(error,results){
    if(error){
      serverResponse(queryParams.name,false);
    }else{
      console.log("No errors!");
      serverResponse(queryParams.name,true);
    }
  });
}

module.exports = {
  CreateTag: CreateTag,
  DeleteTag: DeleteTag,
  EditTag: EditTag
}

文件:mysqlutils.js

var mySql = require('mysql');
var reflectChanges = require('./MySqlReflection.js');
var async = require('async');

/**
 * connects to a MySql database 
 * @param {connection which will be established} connection 
 * @param {paremeters which are executed} queryParams 
 * @param {callback which is required by the async library} callback 
 */
function ConnectToDatabase(connection,queryParams,callback){
  connection.connect(function(error){
    if(error){
      console.log(error);
      throw error;
    }else{
       callback(null,connection,queryParams);
     }
  });
}

/**
 * closes an existing connection to the MySql database
 * @param { connection which is passed from the previous function } connection 
 * @param { callback when database connection was successfully closed } callback 
 */
function CloseDatabaseConnection(connection,queryParams,callback)
{
  connection.end(function(error)
  {
    if(error){
        throw error;
    }else{
      callback(null,connection,queryParams);
    }
  });
}

/**
 * get all files which will be affected by the particular query
 * @param {*} connection 
 * @param {*} queryParams 
 * @param {*} callback 
 */
function GetAffectedFiles(connection,queryParams,callback)
{
    const query = "SELECT Name,Tags FROM Tag";
    const params = [];
    var affectedRows = [];

    connection.query(query,params,function(error,results,fields){
        if(error){
            return connection.rollback(function(){
                throw error;
            });
        }else{
            for(var currRow = 0; currRow < results.length; currRow++)
            {
                if(results[currRow].Name === queryParams.name){
                    affectedRows.push(results[currRow].Name);
                }
            }
        }
        queryParams.affectedRows = affectedRows;
        callback(connection,queryParams,callback);
    });
}

/**
 * inserts a new tag into the database
 * @param { connection which will be passed from the previous function } connection 
 * @param { field values of the original row } queryParams 
 * @param { callback called when query was executed successfully } callback 
 */
function InsertTagIntoDatabase(connection,queryParams,callback){
  const query = "INSERT INTO Tag(Id,Name,Description,Parent,Creator,Admin) VALUES((SELECT UUID()),?,?,?,?,?)";
  const params = [queryParams.name,queryParams.description,queryParams.parent,queryParams.creator,queryParams.admin];
  connection.query(query,params,function(error,results,fields){
    if(error){
      throw error;
      throw error;
    }else{
      callback(null,connection,queryParams);
    }
  });
}

/**
 * process chain which allows will be triggered upon tag deletion
 * @param { connection which was established between } connection 
 * @param { queryParameters which will be passed to subroutines } queryParams 
 * @param { callback which will be called upon termination } callback 
 */
function ReflectTagRemoval(connection,queryParams,callback){
  async.waterfall([
    function SetupPrequisites(callback){
      callback(null,connection,queryParams);
    },
    reflect.DeleteTagEntry,
    reflect.UpdateChildrenTag,
    reflect.UpdateFileTags,
    function PassFurther()
    {
      callback(null,connection,queryParams);
    }
  ]);
}

function ReflectTagUpdate(connection,queryParams,callback){
  async.waterfall([
    function SetupPrequisites(callback){
      callback(null,connection,queryParams);
    },
    ConnectToDatabase,
    reflectChanges.EditTagEntry,
    reflectChanges.EditTagChildrenAfterChanges,
    reflectChanges.UpdateFileTagsAfterEdit,
    function PassFurther(callback){
      callback(null,connection,queryParams);
    }
  ]);
}

function ValidateLoginCredentials(connection,loginCredentials,callback)
{
  const query = "SELECT Name,Password FROM User WHERE Name = ? AND Password = ?";
  const params = [loginCredentials.username,loginCredentials.password];

  connection.query(query,params,function(error,results,fields){
    if(error)
    {
      throw error;
    }
    callback(null,connection);
  });
}

module.exports = 
{
  ConnectToDatabase: ConnectToDatabase,
  InsertTagIntoDatabase: InsertTagIntoDatabase,
  ReflectTagRemoval: ReflectTagRemoval,
  ReflectTagUpdate: ReflectTagUpdate,
  ValidateLoginCredentials: ValidateLoginCredentials,
  CloseDatabaseConnection : CloseDatabaseConnection
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题