【问题标题】:Ajax call completes before all node callbacks are executedAjax 调用在所有节点回调执行之前完成
【发布时间】:2017-05-24 14:29:12
【问题描述】:

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

$.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);
});

这个自定义模块使用嵌套回调来执行多个数据库函数:

//#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()。是否只能在节点的最后一次回调完成后才弹出警报?

谢谢

【问题讨论】:

    标签: javascript jquery ajax node.js callback


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多