我正在编写一个应用程序,它允许您通过表单中的Ajax Post调用向案例添加访问(访问日期、访问类型、注释)。访问创建功能允许您在多个日期添加相同的访问类型和注释。因此,我最终得到一个访问对象,其中包含一系列日期,但具有相同的注释和访问类型。因为我不应该在SQL中执行任何循环,所以我希望在节点中执行它,因为我能够处理数组中的任何故障或单个SQL调用返回的结果。
我尝试设置过程调用,以便它根据
here
但是我不能让它工作,所以我又回到了循环中。
我现在面临的问题是在我得到任何结果之前完成回调。很明显,这是因为我对回拨的理解不够,而且没有多少阅读能让它更清晰,所以我最终来到这里寻求帮助。
下面是执行的代码。作为insertvisit函数参数的visit对象是上面提到的带有日期数组的类。
this.insertVisit = function (req, res, visit)
{
var insertVisit = new Visit();
insertVisit = visit;
var success = 0;
var visitId = 0;
//Split the visits into an array of individual dates
var allVisits = insertVisit.visitDates.split(',');
//Attemp to call insertVisits using a callback
insertVisits(0, function(err){
if( err ) {
console.log('yeah, that insert didnt work: '+ err)
}
});
console.log('finished');
function insertVisits(v)
{
//Loop through all of the visits
if (v < allVisits.length )
{
//Attempt to call the next function
singleDate(allVisits[v], function(err)
{
if(err)
{
console.log(err);
}
else
{
//if everything is successful, insert the next individual date
allVisits[v + 1];
}
})
}
}
function singleDate(singleVisitDate)
{
var query = 'CALL aau.sp_InsertVisit (?,?,?,?,?,?,?,@visitId,@success); SELECT @visitId, @success;';
var parts = singleVisitDate.split('-');
var formattedDate = new Date(parts[2], parts[1] - 1, parts[0]);
connection.init();
//Everything runs fine up to here, but as soon as we go to the next line, the program
//continues back at the end of the loop in the insertVisits function an exits the function.
//At this point the below code executes asynchronously and inserts one of the dates before returning
//and doesn't call any further dates.
connection.acquire(function (err, con)
{
con.query(query,
[
insertVisit.caseId,
formattedDate,
parseInt(insertVisit.visitTypeId),
parseInt(insertVisit.visitStatusId),
insertVisit.adminNotes,
insertVisit.operatorNotes,
insertVisit.isDeleted,
visitId,
success
]
, function (err, result)
{
if(err)
{
console.log(err);
}
else
{
con.release();
res.write(JSON.stringify(result));
}
})
})
}
因此,我尝试遍历每个日期,并为每个日期调用存储过程,并使用res.write将结果添加到响应中。
这是一个全新的项目,非常乐意用承诺或异步/等待来重写它。但是任何例子都会非常感谢通过多个过程调用循环