I am new to javascript, trying to understand async function invocation. Here is my js program:
var notify = function () {
console.log('before');
doPost('data', (res) => {
console.log('callback received');
});
console.log('after');
}
var doPost = function (data) {
console.log(data);
while (true) {
//do nothing
}
}
notify();
If my understanding is correct, notify()-->doPost() is async manner, therefore 'after' should be printed immediately after 'before'. But that does not happen. My program wait infinite loop to complete first. I know there is some loophole in my understanding. Please help.
I tried these below two programs: This one again shows sync behavior. Prints:- before data
var notify = function () {
console.log('before');
doPost('data').then((res) => {
console.log('callback received');
});
console.log('after');
}
var doPost = function (data) {
console.log(data);
return new Promise((resolve, reject) => {
resolve('resolved');
while (true) {
//do nothing
}
});
};
notify();
However if I just remove the infinitely running while loop, it start showing async behaviour. Prints:- before data after callback received
var notify = function () {
console.log('before');
doPost('data').then((res) => {
console.log('callback received');
});
console.log('after');
}
var doPost = function (data) {
console.log(data);
return new Promise((resolve, reject) => {
resolve('resolved');
while (false) {
//do nothing
}
});
};
notify();
This is beyond my understanding. Any help would be highly appreciated.