Ajax调用在执行所有节点回调之前完成

时间:2017-01-10 07:09:55

标签: javascript jquery ajax node.js callback

我正在尝试对节点服务器进行ajax post调用,然后在调用完成后重定向用户。这是我的jquery函数,用于发布ajax调用

$.ajax({
  url: '/myUrl', 
  type: 'POST',
  data: { myParam: myParam,fileName: finalName},
  success: function(data, status){
    alert('Ajax call completed!');
    customFunction(status);

  }, 
  error: function(xOptions, textStatus){
    alert('Error occured!: '+textStatus);
  }
});

现在,在服务器端,我正在处理此请求:

var modCust = require('./custom-module')

app.post('/myUrl',function(req,res){
  var myParam = req.body.myParam;
  var fileName = req.body.fileName;

  var cli = modCust.parseExcel(fileName,myParam);
  res.send(cli);
});

并且此自定义模块使用嵌套回调来执行多个db函数:

//#custom-module.js

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

        return recordset;
    });
};

parseFile: function(filePath, myParam){
  var strSQL = "<sample query>";
  executeQuery(strSQL,'<QueryType>','<table_name>',processDB1,myParam);
},

processDB1: function(myParam){
  var strSQL = "<sample query>";
  executeQuery(strSQL,'<QueryType>','<table_name>',processDB2,myParam);
},

processDB2: function(myParam){
  var strSQL = "<sample query>";
  executeQuery(strSQL,'<QueryType>','<table_name>',processDB3,myParam);
},

processDB3: function(myParam){
  var strSQL = "<sample query>";
  executeQuery(strSQL,'<QueryType>','<table_name>');
},

但问题是,即使在所有回调完成之前,也会在processDB3()之前执行警报调用。只有在从节点完成最后一次回调后才可以弹出警报吗?

由于

1 个答案:

答案 0 :(得分:0)

你需要在javascript中查看promises。函数parseExcel应返回promise,以便您可以执行以下操作:

modCust.parseExcel(fileName,myParam).then(function(resultFromParseExcelFunction) {
    res.send(resultFromParseExcelFunction)
})

查看node package q以轻松实现承诺。