[英]function returning undefined when using
我有一個連接到MsSQL數據庫的函數來獲取一些數據並構建一個文本語句,這里是:
function getActions(issue_id, callback){
var action = '';
var conn2 = new sql.Connection(config, function(err) {
if(err){
showNotification('error connecting for selecting actions for ALL issues: ' + err.message, 'danger', 'glyphicon glyphicon-tasks');
} else {
var request = new sql.Request(conn2);
request
.input('issue_id', sql.Int,issue_id)
.query('SELECT [date], [description] FROM [actions] WHERE [issue_id] = @issue_id')
.then(function(data2) {
action ='<tr>'+
'<td style="vertical-align: top;" class="bold">action:</td>'+
'<td>'+
'<table>';
data2.forEach(function(data21){
action +='<tr>'+
'<td>'+data21.date+'</td>'+
'<td>'+data21.description+'</td>'+
'</tr>';
});
action += '</table>'+
'</td>'+
'</tr>'+
'</tbody>'+
'</table>';
console.log(action);
callback(null, action);
}).catch(function(error) {
showNotification('Error on selecting actions for ALL issues:' + error.message, 'danger', 'glyphicon glyphicon-tasks');
});
}
});
}
但是當我在我的代碼中的另一個地方使用該函數它返回undefined而不是text語句時,我在return語句之前創建一個console.log(action)它返回正確的文本.....我沒有得到它為什么在使用函數時返回undefined
更新當我使用Aruna的功能我正在使用這樣的功能:
for(let b=0;b<id.length;b++){
getActions(id[b],function(err, action) {
arrAction[b] = action;
});
}
當您異步連接和查詢MySQL數據庫時,您不能指望同步返回數據。
您應該使用'callback'來處理這個問題。
所以你的代碼可以是這樣的,
function getActions(issue_id, callback){
var action = '';
var conn2 = new sql.Connection(config, function(err) {
if(err){
showNotification('error connecting for selecting actions for ALL issues: ' + err.message, 'danger', 'glyphicon glyphicon-tasks');
} else {
var request = new sql.Request(conn2);
request
.input('issue_id', sql.Int,issue_id)
.query('SELECT [date], [description] FROM [actions] WHERE [issue_id] = @issue_id')
.then(function(data2) {
action ='<tr>'+
'<td style="vertical-align: top;" class="bold">action:</td>'+
'<td>'+
'<table>';
data2.forEach(function(data21){
action +='<tr>'+
'<td>'+data21.date+'</td>'+
'<td>'+data21.description+'</td>'+
'</tr>';
});
action += '</table>'+
'</td>'+
'</tr>'+
'</tbody>'+
'</table>';
console.log(action);
callback(null, action);
}).catch(function(error) {
showNotification('Error on selecting actions for ALL issues:' + error.message, 'danger', 'glyphicon glyphicon-tasks');
});
}
});
}
你應該像這樣打電話,
var issue_id = 12;
getActions(issue_id, function(err, action) {
// to do
});
另外,像這樣改變你的for循環,就像在循環中調用異步函數一樣,for循環變量“b”將在響應來自函數之前被更改
var arrAction = [];
for(let b=0;b<id.length;b++){
getActions(id[b],function(err, action) {
arrAction[arrAction.length] = action;
});
}
getActions
不會返回任何內容。
在內部函數中調用return action
,與sql.Connection
類有關。 也許你應該return conn2;
在getActions
結束時? 沒有關於你在做什么的背景很難說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.