The following case: I have a wrapperfunction "InitializePage()" which is called when loading the page. This one contains the functions a-d out of which a and b contain AJAX. It would look like this:
function wrapperFunction() {
a() //contains AJAX
b() //contains AJAX
c() //Synchronous
d() //Synchronous
}
Now, I want function b to start only if function a has finished already. I know that I could easily do this by making the wrapperFunction "async", use "await" in front of function a and then return the promise from function a (using JQuery Ajax) like this:
function a() {
return $.post('somefile.php', {
//someCode
})
}
But I want to know one thing: function a by itself should be treated by JS as SYNCHRONOUS code until it hits the JqueryAJAX inside the function, right? Only when it hits the AJAX call, JS hands it off to the C++ API and continues to the next bit of code no matter whether the AJAX call has finished execution yet or not, right?
So lets assume, even though it would be unnecessarily hacky, I would do this:
async function a() {
await $.post('someFile.php', {
//some code
})
}
Since I synchronized the AJAX part of function a(), would this mean that at the level of wrapperFunction(), JS does NOT procede until function a() and all of its contents have finished execution?
The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.
So as per your question.
async function a() {
await $.post('someFile.php', {
//some code
})
}
yes it makes it asynchronous. but it is always better to use await where we are calling this function something like below.
for more refrenece please take a look here.
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}
asyncCall();