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

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

问题描述:

我试图对节点服务器进行ajax post调用,然后在调用完成后重定向用户。这里是我的制作后Ajax调用在执行所有节点回调之前完成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); 
    } 
}); 

现在,在服务器端,我处理这个请求作为jQuery函数:

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中的承诺。该功能ParseExcel的应返回的承诺,让您可以根据以下步骤做:

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

退房node package q实现简单的方式承诺。