简体   繁体   English

只有在nodejs路由器上完成所有事务后,才返回到ajax调用

[英]Return to ajax call only after all transactions are completed on nodejs router

I am trying to make an ajax call to a node page, which performs some operations to the database, based on the parameters passed in the ajax calls. 我正在尝试对节点页面进行ajax调用,该节点页面根据ajax调用中传递的参数对数据库执行一些操作。 The issue I am facing is that the control is passed back to the html page(I am using an alert to test the request completion) which initiated the ajax call even before all the DB transactions are completed on the nodejs end. 我面临的问题是,该控件被传递回html页面(我正在使用警报来测试请求完成),该页面甚至在nodejs端上的所有数据库事务都已完成之前就启动了ajax调用。 I have added a smaller version of the code for better understanding. 我添加了一个较小的代码版本,以更好地理解。

Origin: HTML page
<div id="paramList">
    <form action='import/other' method='POST' style='display:none;' id="h_form">
    <label><input type="checkbox" value="opt1" />Option 1</label>
    <label><input type="checkbox" value="opt2" />Option 2</label>
    <label><input type="checkbox" value="opt3" />Option 3</label>
    <label><input type="checkbox" value="opt4" />Option 4</label>
    <label><input type="checkbox" value="opt5" />Option 5</label>
    </form>
</div>
<button onclick="startValidation()">Submit</button>

Handler: JS
function startValidation() {
    var paramlist = '';
    $("#paramList input[type='checkbox']").each(function() {
        if ($(this).is(":checked")) {
            paramlist += "'" + $(this).val() + "',";
        }
    });
    paramlist = paramlist.substr(0, paramlist.length - 1);

    var req = $.ajax({
        url: '/import/validate',
        type: 'POST',
        data: { paramList: paramlist, fileName: finalName }
    })
    req.done(function(data, status) {
        alert('Data validated successfully. Select Ok to go to validate sheet: ' + status);
        var form = $("#h_form");
        form.submit();
        //redirect to the other page and load data from the latest insert
    });
    req.fail(function(xOptions, textStatus) {
        alert('Error occured!: ' + textStatus);
    });

}

Server side script 服务器端脚本

NodeJS: Router
router.post('/validate',function(req,res){
    var paramlist = req.body.paramList;
    var fileName = req.body.fileName;
    var cli = modImport.parseFile(fileName,paramlist);
    res.send(cli);
});

//Import module: modImport.js
module.exports.executeQuery = function(strSQL, operationType, tableName, cb, param) {
    logger.log('debug','running query: '+strSQL);

    var request = new sql.Request(connection);
    request.query(strSQL,function(err, recordset) {
        if(err){
            logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
        }
        logger.info(operationType+' ON '+tableName+' successful!');
        if(cb){
            cb(param);
        }
    });

},

module.exports.parseFile: function(filePath, validateParam){
    sql.connect(config).then(function() {
        var arr = [];
        arr.push(data);arr.push(validateParam);
        arr.push(tName);

        var delQ = "DELETE FROM [Tbl_TempData]";
        util.executeQuery(delQ,'DELETION','[Tbl_TempData]', module.exports.bulkImportIntoTempData, arr);

        console.log("deletion completed");

    }).catch(function(err) {
        logger.error('other error: '+err); 
    });
},

module.exports.bulkImportIntoTempData: function(arr){
    var data = arr[0];
    var validateParam = arr[1];
    var tName = arr[2];

    var bInQ = "INSERT INTO [Tbl_TempData] (field1,field2,field3) VALUES ";
    data.forEach(function(rec, index){
        var keys = Object.keys(rec);
        var kLen = keys.length - 1;

        keys.forEach(function(datum,cursor){                
            bInQ += "('" + datum + "','" + rec[datum] + "','" + tName + ")";
            if(cursor < kLen){
                bInQ += ",";
            }
        });
    });
    module.exports.executeQuery(bInQ,'BULK INSERTION','[Omni_TempSurveyData]',module.exports.processForTempCalc,validateParam);
},

module.exports.processForTempCalc: function(validateParam){
    var strSQL = "DELETE FROM [Tbl_TempCalc]";
    util.executeQuery(strSQL,'DELETION','[Tbl_TempCalc]',module.exports.insertIntoTempCalc,validateParam);
},

module.exports.insertIntoTempCalc: function(validateParam){
    var strSQL = "INSERT INTO .....";
    //some transformations here from other tables
    util.executeQuery(strSQL,'INSERTION','[Tbl_TempCalcData]');


},

module.exports.insertIntoBlankCalc: function(validateParam){
    var strSQL = "INSERT INTO .....";

    util.executeQuery(strSQL,'INSERTION','[Tbl_BlankCalcData]');

    //TODO: return the ajax call
}

After the ajax completion, the user is to be redirected to a page which is loading data from the last inserted table. 在ajax完成之后,将用户重定向到正在从最后插入的表中加载数据的页面。 But since the alert is popped up before final insertion, the redirected page is shown blank to the user. 但是由于警报是在最终插入之前弹出的,因此重定向页面对用户显示为空白。 Please suggest how to overcome this scenario. 请提出如何克服这种情况的建议。

if i am right the "modImport.parseFile" function does not return anything and just calls "util.executeQuery" in a promise. 如果我是对的,那么“ modImport.parseFile”函数不会返回任何内容,而只是在promise中调用“ util.executeQuery”。

so in this line "var cli = modImport.parseFile(fileName,paramlist);" 所以在这一行“ var cli = modImport.parseFile(fileName,paramlist);” cli is not valued and raises an error; cli未被重视,并引发错误;

i think you should send "res.send(cli)" as callback for "modImport.parseFile" as parameter and then send it for "util.executeQuery" or you should change your functions 我认为您应该发送“ res.send(cli)”作为“ modImport.parseFile”作为参数的回调,然后发送给“ util.executeQuery”,否则您应该更改功能

update: i changed your code this way. 更新:我以这种方式更改了您的代码。 so i can not run it but i guess it will works. 所以我不能运行它,但我想它将起作用。 hope it helps. 希望能帮助到你。

router.post('/validate',function(req,res){
    var paramlist = req.body.paramList;
    var fileName = req.body.fileName;

    var GLOBAL.response_function = function(err,data) 
    {
        //here you can do anything with your data or err;
        // like that 

        if (err)
        {
            return res.status(404).send(err.toString());
        }
        else 
        {
            // if your data is json
            return res.status(200).send(JSON.stringify(data));
        }
    };

    modImport.parseFile(fileName,paramlist) ;
});

module.exports.executeQuery = function(strSQL, operationType, tableName, cb, param) {
    logger.log('debug','running query: '+strSQL);

    var request = new sql.Request(connection);
    request.query(strSQL,function(err, recordset) {
        if(err){
            logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
        }
        logger.info(operationType+' ON '+tableName+' successful!');

        if(cb){

            if (param.is_return_callback)
            {
                cb(err, recordset)
            }
            else 
            {
                cb(param);
            }
        }


    });

},

the point is you send this ",GLOBAL.response_function, {is_return_callback:true}" by last function which should execute query 关键是您应通过执行查询的最后一个函数发送此“,GLOBAL.response_function,{is_return_callback:true}”

   module.exports.insertIntoTempCalc: function(validateParam){
        var strSQL = "INSERT INTO .....";
        //some transformations here from other tables

        util.executeQuery(strSQL,'INSERTION','[Tbl_TempCalcData]',GLOBAL.response_function, {is_return_callback:true});
    },

if other functions work fine this will resolve the problem: 如果其他功能运行正常,将解决问题:

NodeJS: Router
    router.post('/validate',function(req,res){
        var paramlist = req.body.paramList;
        var fileName = req.body.fileName;
        var cli = modImport.parseFile(fileName,paramlist,function(){  
          res.send(cli);
        });
    });

    //Import module: modImport.js
    module.exports.executeQuery = function(strSQL, operationType, tableName, cb, param) {
        logger.log('debug','running query: '+strSQL);

        var request = new sql.Request(connection);
        request.query(strSQL,function(err, recordset) {
            if(err){
                logger.error('ERROR in '+operationType+' ON '+tableName+': '+err);
            }
            logger.info(operationType+' ON '+tableName+' successful!');
            if(cb){
                cb(param);
            }
        });

    },

    module.exports.parseFile: function(filePath, validateParam,callback){
        sql.connect(config).then(function() {
            var arr = [];
            arr.push(data);arr.push(validateParam);
            arr.push(tName);

            var delQ = "DELETE FROM [Tbl_TempData]";
            util.executeQuery(delQ,'DELETION','[Tbl_TempData]', module.exports.bulkImportIntoTempData, arr);

            console.log("deletion completed");
            callback()

        }).catch(function(err) {
            logger.error('other error: '+err); 
            callback()
        });
    },

    module.exports.bulkImportIntoTempData: function(arr){
        var data = arr[0];
        var validateParam = arr[1];
        var tName = arr[2];

        var bInQ = "INSERT INTO [Tbl_TempData] (field1,field2,field3) VALUES ";
        data.forEach(function(rec, index){
            var keys = Object.keys(rec);
            var kLen = keys.length - 1;

            keys.forEach(function(datum,cursor){                
                bInQ += "('" + datum + "','" + rec[datum] + "','" + tName + ")";
                if(cursor < kLen){
                    bInQ += ",";
                }
            });
        });
        module.exports.executeQuery(bInQ,'BULK INSERTION','[Omni_TempSurveyData]',module.exports.processForTempCalc,validateParam);
    },

    module.exports.processForTempCalc: function(validateParam){
        var strSQL = "DELETE FROM [Tbl_TempCalc]";
        util.executeQuery(strSQL,'DELETION','[Tbl_TempCalc]',module.exports.insertIntoTempCalc,validateParam);
    },

    module.exports.insertIntoTempCalc: function(validateParam){
        var strSQL = "INSERT INTO .....";
        //some transformations here from other tables
        util.executeQuery(strSQL,'INSERTION','[Tbl_TempCalcData]');


    },

    module.exports.insertIntoBlankCalc: function(validateParam){
        var strSQL = "INSERT INTO .....";

        util.executeQuery(strSQL,'INSERTION','[Tbl_BlankCalcData]');

        //TODO: return the ajax call
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM