Understanding asynchronous function calls

134 Views Asked by At

I'm just beginning to learn about asynchronous JavaScript so I'm not sure if this is a silly question, but I could not find an answer to it directly.

In the examples of asynchronous JS I've seen the asynchronous logic is always called after the synchronus logic, that is to say last. Something like:

function1() {}

asynchronousFunction(){}

function2(){}

Isn't this the equivalent of:

function1(){}

function2(){}

function3(){} //asynchronous function

Isn't an asynchronous call the same as a function call at the top of the stack of the main thread, since the asynchronous call is seems to always be made after anything that is synchronous ?

Thanks for any help on this !

3

There are 3 best solutions below

1
On

Asynchronous functions in JS are used to do something that requires time, e.g. downloading some data, or calculating something. Of corse you can do it synchronously but your view will freeze, and no one want that.

It is not true that async functions run after all sync. (It starts like normal synch function but end when 'task' is done.

More: Link

You should also read more about AJAX.

0
On

A Javascript async function starts out as a synchronous function, but differs from regular functions in how it's settled.

Javascript is single-threaded—that is, it can only focus on a single thing at a time. It makes up for this by having promises, which are the main concept on which asynchronous functions are built. When an asynchronous function is called, it creates a promise, which just says, "hey, I'm gonna call back to this later, once foo is done." So, your asynchronous function does complete before it moves onto the next function, but the difference is that it just knows now that it needs to come back later.

The reason it seems your asynchronous function always completes after all the synchronous functions is because, well, it does. Promises are always called after the current run of code, because, again, Javascript can only run on a single thread.

You can read more about promises here.

0
On

Synchronous calls happen line by line. Synchronous lines are called when its previous functions are all called and executed.

Asynchronous calls in javascript wait for some event to take place, before they are called. It schedules the method to be called in future in case a particular event takes place.

Note that asynchronous does not mean the same thing as concurrent or multi-threaded. JavaScript can have asynchronous code, but it is generally single-threaded.

Read more

This is made possible with something called the Event Loop.

Consider the following code snippet.

console.log("1");
setTimeout(() => {
 console.log("2");
},0);
console.log("3");

The output is

1
3
2

This is because line no. 2 is a asynchronous method call. This method gets added to the queue called event loop and then is dequeued in the future, when the timer ends or when the call stack is empty.