[英]Call a function after all currently scheduled callbacks are executed (node)
[英]Ajax call completes before all node callbacks are executed
我正在嘗試向節點服務器進行ajax發布調用,然后在調用完成后重定向用戶。 這是我的jquery函數,用於進行post 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);
});
並且此自定義模塊使用嵌套的回調來執行多個數據庫功能,如下所示:
//#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中的Promise。 函數parseExcel應該返回promise,以便您可以執行以下操作:
modCust.parseExcel(fileName,myParam).then(function(resultFromParseExcelFunction) {
res.send(resultFromParseExcelFunction)
})
簽出節點包q ,以輕松方式實現承諾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.