【发布时间】:2019-02-09 03:21:44
【问题描述】:
我正在编写一个应用程序,它允许您通过表单中的 Ajax POST 调用将访问(访问日期、访问类型、注释)添加到案例中。访问创建功能允许您在多个日期添加相同的访问类型和注释。所以我最终得到了一个包含日期数组的访问对象,但注释和访问类型相同。因为 SQL 不是我应该执行任何循环的地方,所以我想在 Node 中执行它,因为我将能够处理数组中的任何故障或从各个 SQL 调用返回的结果。
我尝试设置过程调用,以便根据here 将数组中的数组作为参数,但我无法让它工作,所以我回退到循环。
我遇到的问题是回调在我得到任何结果之前完成。显然是因为我对回调的理解不够,再多的阅读也无法使其更清楚,所以我最终来到这里寻求帮助。
下面是执行的代码。作为insertVisit函数的参数的访问对象是上面提到的带有日期数组的类。
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 将结果添加到响应中。
这是一个全新的项目,很高兴用 Promise 或 asynch/await 重写它。但是任何例子都会非常感谢循环多个过程调用
【问题讨论】:
标签: javascript mysql node.js loops stored-procedures