I am writing client-side javascript functions to send post request to server and to get result. I am using such resources in my work:
- https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
- https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
- How do I resolve additional post request in onSubmit method in React (I do not use react, just regular javascript. Answers there mention async-await mechanism which helps you to avoid spinning callbacks).
Here is my code:
Html part - button that triggers Javascript:
<button class="btn btn-success greenbtn" id="btnFinishDay" onclick="btnFinishDay_click(event)" name="btnFinishDay" >GO</button></div>
Here is button handler:
async function btnFinishDay_click(eee) {
var txtBarCodeValue = document.getElementById("txtBarCode").value;
var rrr = await postAjaxWithFetch('/CheckItem', { barcodeValue: txtBarCodeValue });
console.log(rrr);
alert("CheckCustomer request was sent");
}
Here is how I send post request:
/*
A modern way to use POST request with form data and ajax.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
*/
async function postAjaxWithFetch(url, data) {
// if data is string then use it as is. If it is Object then generate formdata string from it
var params = typeof data == 'string' ? data : Object.keys(data).map(
function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) }
).join('&');
const request1 = new Request(url, {
method: "POST",
body: params,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const response1 = await fetch(request1);
console.log(response1);
alert("hello from postAjaxWithFetch")
return response1;
}
unfortunately right after statement with await is reached then subroutine quits. In debugger I see:
btnFinishDay_clickis enteredawait postAjaxWithFetchcall is reachedpostAjaxWithFetchfunction is enteredconst response1 = await fetch(request1)is reachedpostAjaxWithFetchis stepped out, noconsole.logand noalertis called- Network monitor does not show any /CheckItem request
- btnFinishDay_click finishes, no alert is shown
To sum it up - no alert calls are processed. And this feels confusing for me...
Question is: Why does async and await in regular javascript act like this disrupting normal flow?