This is the essence of what I'm trying to do...
Creating a simple page that let's users submit a vacation request. If the request if of type 'Leave of Absence', then a note is required. So, if the request type is 'Leave of Absence', do an Ajax call to the server to get the note count for this request. If it's zero, stop the process. If it's > 0, then save the request.
I'm trying to do this with a promise, but I'm doing something wrong....
for (var i = 0; i < VacationRequests.length; i++)
{
if (VacationRequests[i].VacationRequestType == leaveOfAbsenceType)
{
GetNoteCountPromise.then(function(result) {
SaveVacationRequest(VacationRequests[i]);
}, function(err) {
$('#LeaveOfAbsenceModal').modal('show');
return;
});
}
}
And here's the promise...
var GetNoteCountPromise = new Promise(function(resolve, reject) {
$.ajax({
url: '@Url.Action("GetNoteCount", "VacationRequests")',
type: 'GET',
dataType: 'json',
data: { VacationRequestId: vacationRequestId },
success: function(data) {
if (data > 0) {
resolve(true);
}
else {
reject(false);
}
}
});
});
First question:
I somehow need to pass vacationRequestId
into the promise. Not sure how to do that.
Second question:
Am I doing this right?
EDIT:
This what I did first:
for (var i = 0; i < VacationRequests.length; i++)
{
if (VacationRequests[i].VacationRequestType == leaveOfAbsenceType)
{
$.ajax({
url: '@Url.Action("GetNoteCount", "VacationRequests")',
type: 'GET',
dataType: 'json',
data: { VacationRequestId: vacationRequestId },
success: function(data) {
if (data > 0) {
SaveVacationRequest(VacationRequests[i]); /// THIS is where it broke down
}
else {
$('#LeaveOfAbsenceModal').modal('show');
return;
}
}
});
}
}
The problem with this, is that by the time we hit the Success method, the loop had finished and VacationRequests[i]
was undefined.