How much further does code execute after an asynchronous function is called - javascript

Apologies if the title of this question is slightly confusing, I was struggling to find a way to word this.
Basically, when an asynchronous function is called, how much further down the code will be executed if the asynchronous function is called from other functions, objects, or files. For example:
function func1() {
// async function 1
// async function 2
}
function func2() {
// more code
}
func1();
func2();
Let's say we execute func1() and both the async functions inside of it take a very long time to run. Will we continue on to func2() while the content of func1() is still being run, or will we block until func1() is finished before continuing to func2()?

JavaScript is single threaded, non-blocking and asynchronous language. JavaScript has call stack, event loop and a callback queue. Words are taken directly from this video. Javascript works on v8 engine (chrome), spider monkey (firefox) which provide JavaScript call stack and heap. v8 or spider monkey provide call stack to Javascript so whenever a function is called, it is stored in the call stack of the runtime (browser in our case, local if you have node installed). Browser also provide the web apis to the javascript like setTimeOut, XMLHttpRequest and DOM. The pictorial illustration is something like this. (Source is the same video which I've tagged.)
JavaScript is single threaded and it means it can execute one function at a time as it has only one call stack. So whenever an asynchronous code (inside func1)is executing, it is executed through webAPIs provided by the browser. The role of callback queues come here. Whenever the result from the Async code is executed, it is stored in the callback queue and it waits for the stack to get empty (event driven programming). Whenever it sees that the stack is empty, the function from the callback queues will start executing.
In your case, you're calling func1, it kicks in some async code but currently func1 is in stack. If the async code has completed and if it sees the stack as empty, it will executed the async code first and then func2 but if the async code hasn't completed, it will start executing the func2 and the callback queue will wait for the stack to get empty. In this case, the flow will be func1 --> func2 --> async code.
So, it is matter of timing. For async code, if the code has returned and waiting in callback queue, as soon as it sees the stack empty, it will kick in and start executing the callbacks (.then or callback from setTimeOut etc.) I'll recommend you to watch that video for better insights and what an event loop in JS is. If I'm missing out something, anyone please feel free to edit this answer or provide suggestions for edit.

JavaScript is single threaded, it literally means nothing can be executed in the same time. If your code has asynchronous nature it means that it is executed in uknown future. I said uknown because it depends from the code. For example asynchronous code for ajax call will be executed when the browser gets the response from the server.
That said, the async code is not executed in the declaration moment but in uknown next event loop. Furthermore it not blocks the current execution. In javascript your execution code can not be disturbed. It just runs through all lines.
Going back to the example, if func1 has no sync blocking code then func2 will be executed right away without any delay.

Asynchronous callback are top level events (similar to button click events) and can only be started when there is no other scripts executing.
Execution will continue till call stack is empty (including "global user code" which what your sample shows) and script engine itself gets control back - so both func1() and func2() will finish before callbacks are executed.
Note: you can't rely on such behavior for normal code - if "asynchronous" function has both synchronous and asynchronous code branches callback from that function can be executed synchronously without even returning to calling function (this can happen with plain callbacks or any other form including promises).

Related

NodeJS setInterval() running parallel to loop using async [duplicate]

I am thinking about it and this is what I came up with:
Let's see this code below:
console.clear();
console.log("a");
setTimeout(function(){console.log("b");},1000);
console.log("c");
setTimeout(function(){console.log("d");},0);
A request comes in, and JS engine starts executing the code above step by step. The first two calls are sync calls. But when it comes to setTimeout method, it becomes an async execution. But JS immediately returns from it and continue executing, which is called Non-Blocking or Async. And it continues working on other etc.
The results of this execution is the following:
a c d b
So basically the second setTimeout got finished first and its callback function gets executed earlier than the first one and that makes sense.
We are talking about single-threaded application here. JS Engine keeps executing this and unless it finishes the first request, it won't go to second one. But the good thing is that it won't wait for blocking operations like setTimeout to resolve so it will be faster because it accepts the new incoming requests.
But my questions arise around the following items:
#1: If we are talking about a single-threaded application, then what mechanism processes setTimeouts while the JS engine accepts more requests and executes them? How does the single thread continue working on other requests? What works on setTimeout while other requests keep coming in and get executed.
#2: If these setTimeout functions get executed behind the scenes while more requests are coming in and being executed, what carries out the async executions behind the scenes? What is this thing that we talk about called the EventLoop?
#3: But shouldn't the whole method be put in the EventLoop so that the whole thing gets executed and the callback method gets called? This is what I understand when talking about callback functions:
function downloadFile(filePath, callback)
{
blah.downloadFile(filePath);
callback();
}
But in this case, how does the JS Engine know if it is an async function so that it can put the callback in the EventLoop? Perhaps something like the async keyword in C# or some sort of an attribute which indicates the method JS Engine will take on is an async method and should be treated accordingly.
#4: But an article says quite contrary to what I was guessing on how things might be working:
The Event Loop is a queue of callback functions. When an async
function executes, the callback function is pushed into the queue. The
JavaScript engine doesn't start processing the event loop until the
code after an async function has executed.
#5: And there is this image here which might be helpful but the first explanation in the image is saying exactly the same thing mentioned in question number 4:
So my question here is to get some clarifications about the items listed above?
1: If we are talking about a single-threaded application, then what processes setTimeouts while JS engine accepts more requests and executes them? Isn't that single thread will continue working on other requests? Then who is going to keep working on setTimeout while other requests keep coming and get executed.
There's only 1 thread in the node process that will actually execute your program's JavaScript. However, within node itself, there are actually several threads handling operation of the event loop mechanism, and this includes a pool of IO threads and a handful of others. The key is the number of these threads does not correspond to the number of concurrent connections being handled like they would in a thread-per-connection concurrency model.
Now about "executing setTimeouts", when you invoke setTimeout, all node does is basically update a data structure of functions to be executed at a time in the future. It basically has a bunch of queues of stuff that needs doing and every "tick" of the event loop it selects one, removes it from the queue, and runs it.
A key thing to understand is that node relies on the OS for most of the heavy lifting. So incoming network requests are actually tracked by the OS itself and when node is ready to handle one it just uses a system call to ask the OS for a network request with data ready to be processed. So much of the IO "work" node does is either "Hey OS, got a network connection with data ready to read?" or "Hey OS, any of my outstanding filesystem calls have data ready?". Based upon its internal algorithm and event loop engine design, node will select one "tick" of JavaScript to execute, run it, then repeat the process all over again. That's what is meant by the event loop. Node is basically at all times determining "what's the next little bit of JavaScript I should run?", then running it. This factors in which IO the OS has completed, and things that have been queued up in JavaScript via calls to setTimeout or process.nextTick.
2: If these setTimeout will get executed behind the scenes while more requests are coming and in and being executed, the thing carry out the async executions behind the scenes is that the one we are talking about EventLoop?
No JavaScript gets executed behind the scenes. All the JavaScript in your program runs front and center, one at a time. What happens behind the scenes is the OS handles IO and node waits for that to be ready and node manages its queue of javascript waiting to execute.
3: How can JS Engine know if it is an async function so that it can put it in the EventLoop?
There is a fixed set of functions in node core that are async because they make system calls and node knows which these are because they have to call the OS or C++. Basically all network and filesystem IO as well as child process interactions will be asynchronous and the ONLY way JavaScript can get node to run something asynchronously is by invoking one of the async functions provided by the node core library. Even if you are using an npm package that defines it's own API, in order to yield the event loop, eventually that npm package's code will call one of node core's async functions and that's when node knows the tick is complete and it can start the event loop algorithm again.
4 The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed.
Yes, this is true, but it's misleading. The key thing is the normal pattern is:
//Let's say this code is running in tick 1
fs.readFile("/home/barney/colors.txt", function (error, data) {
//The code inside this callback function will absolutely NOT run in tick 1
//It will run in some tick >= 2
});
//This code will absolutely also run in tick 1
//HOWEVER, typically there's not much else to do here,
//so at some point soon after queueing up some async IO, this tick
//will have nothing useful to do so it will just end because the IO result
//is necessary before anything useful can be done
So yes, you could totally block the event loop by just counting Fibonacci numbers synchronously all in memory all in the same tick, and yes that would totally freeze up your program. It's cooperative concurrency. Every tick of JavaScript must yield the event loop within some reasonable amount of time or the overall architecture fails.
Don't think the host process to be single-threaded, they are not. What is single-threaded is the portion of the host process that execute your javascript code.
Except for background workers, but these complicate the scenario...
So, all your js code run in the same thread, and there's no possibility that you get two different portions of your js code to run concurrently (so, you get not concurrency nigthmare to manage).
The js code that is executing is the last code that the host process picked up from the event loop.
In your code you can basically do two things: run synchronous instructions, and schedule functions to be executed in future, when some events happens.
Here is my mental representation (beware: it's just that, I don't know the browser implementation details!) of your example code:
console.clear(); //exec sync
console.log("a"); //exec sync
setTimeout( //schedule inAWhile to be executed at now +1 s
function inAWhile(){
console.log("b");
},1000);
console.log("c"); //exec sync
setTimeout(
function justNow(){ //schedule justNow to be executed just now
console.log("d");
},0);
While your code is running, another thread in the host process keep track of all system events that are occurring (clicks on UI, files read, networks packets received etc.)
When your code completes, it is removed from the event loop, and the host process return to checking it, to see if there are more code to run. The event loop contains two event handler more: one to be executed now (the justNow function), and another within a second (the inAWhile function).
The host process now try to match all events happened to see if there handlers registered for them.
It found that the event that justNow is waiting for has happened, so it start to run its code. When justNow function exit, it check the event loop another time, searhcing for handlers on events. Supposing that 1 s has passed, it run the inAWhile function, and so on....
The Event Loop has one simple job - to monitor the Call Stack, the Callback Queue and Micro task queue. If the Call Stack is empty, the Event Loop will take the first event from the micro task queue then from the callback queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.
As most developers know, that Javascript is single threaded, means two statements in javascript can not be executed in parallel which is correct. Execution happens line by line, which means each javascript statements are synchronous and blocking. But there is a way to run your code asynchronously, if you use setTimeout() function, a Web API given by the browser, which makes sure that your code executes after specified time (in millisecond).
Example:
console.log("Start");
setTimeout(function cbT(){
console.log("Set time out");
},5000);
fetch("http://developerstips.com/").then(function cbF(){
console.log("Call back from developerstips");
});
// Millions of line code
// for example it will take 10000 millisecond to execute
console.log("End");
setTimeout takes a callback function as first parameter, and time in millisecond as second parameter.
After the execution of above statement in browser console it will print
Start
End
Call back from developerstips
Set time out
Note: Your asynchronous code runs after all the synchronous code is done executing.
Understand How the code execution line by line
JS engine execute the 1st line and will print "Start" in console
In the 2nd line it sees the setTimeout function named cbT, and JS engine pushes the cbT function to callBack queue.
After this the pointer will directly jump to line no.7 and there it will see promise and JS engine push the cbF function to microtask queue.
Then it will execute Millions of line code and end it will print "End"
After the main thread end of execution the event loop will first check the micro task queue and then call back queue. In our case it takes cbF function from the micro task queue and pushes it into the call stack then it will pick cbT funcion from the call back queue and push into the call stack.
JavaScript is high-level, single-threaded language, interpreted language. This means that it needs an interpreter which converts the JS code to a machine code. interpreter means engine. V8 engines for chrome and webkit for safari. Every engine contains memory, call stack, event loop, timer, web API, events, etc.
Event loop: microtasks and macrotasks
The event loop concept is very simple. There’s an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps, waiting for more tasks
Tasks are set – the engine handles them – then waits for more tasks (while sleeping and consuming close to zero CPU). It may happen that a task comes while the engine is busy, then it’s enqueued. The tasks form a queue, so-called “macrotask queue”
Microtasks come solely from our code. They are usually created by promises: an execution of .then/catch/finally handler becomes a microtask. Microtasks are used “under the cover” of await as well, as it’s another form of promise handling. Immediately after every macrotask, the engine executes all tasks from microtask queue, prior to running any other macrotasks or rendering or anything else.

How is a function made inherently asynchronous in JavaScript

I have been trying to understand how asynchronous JavaScript works. From what I understand, the language is by-default synchronous and single-threaded.
Synchronous in the sense that during the processing of the current task, rest of the code is blocked.
Single-Threaded in the sense that only one sequence of functions is loaded at a time. To me, both of these concepts sound a bit similar.
I'm aware of how callbacks, promises and async/await keywords help in dealing with asynchronous code. But what I don't understand is, how a block of code is made asynchronous. For example, this is a code from javascript.info:
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
Now, when this function is called, it is supposed to be "asynchronous", in the sense that it won't block the subsequent lines of code from execution, but will carry on it's work "in the background".
loadScript('/my/script.js');
// the code below loadScript
// doesn't wait for the script loading to finish
// ...
What I don't understand is, what part of the function defined above made it asynchronous? The same goes for browser and API functione like fetch() and addEventListener(). What in their implementation made them asynchronous? How is task made to be performed in the background without blocking the rest of the code?
"What part of the function defined above made it asynchronous?"
The above function runs synchronously, but this calls for explanation. In general:
Event Loop
Browsers use an event loop to process "everything", including repainting the screen,
calling JavaScript code when timers expire, promises become settled, events have occurred and need to be fired on DOM elements, or in general calling JavaScript in response to an external event.
Single Thread
The event loop's task manager does not continue with other tasks after passing control to the JavaScript engine to execute JavaScript code. This is the "single threaded" part. JavaScript execution continues until it runs to completion, either by running to the end of top-level execution flow within a script element, or by returning from a call out from the event loop.
Single threading prevents JavaScript execution being interrupted by call outs from the event loop in a different thread with the ability to access the same program scope - which has the potential to corrupt data and program state. Effectively single threading eliminates the need to implement a disable/enable interrupts system in JavaScript.
Note: Multiple JavaScript threads can be created by setting up worker threads running in separate CPU threads. But communication between threads is tightly controlled and they do not share the same program scope.
Blocking
The cost of single threading is that execution of JavaScript in the main thread prevents the event loop task manager from proceeding with anything else. Hence executing JavaScript will block screen updating and responding to user input etc. until it returns to the event loop.
Synchronous
Synchronous code means code executed in a single call out from the event loop. Synchronous code execution flow proceeds through sequential, branch and looping constructs as you would read it in source code.
A synchronous API call is one that returns it result back to the caller with a return statement - without using a callback function or promise to supply the result.
Asynchronous
Asynchronous code is relative to something else: it is code that is not executed in the same call out from the event loop as some other execution context. E.G. a call back function passed to setTimeout is never called before the code that calls setTimeout returns to the event loop, so the call back is said to be called "asynchronously".
async Functions
Functions declared with the async keyword are a special case by design. Briefly
the await operator returns to the event loop when executed. Hence code using the result of an await operator runs asynchronously with respect to code which executed the await operator (or prepared its operand).
async functions always return a promise for the function's return value, not the returned value itself. Since promise values are not available synchronously, async function results can not be obtained synchronously in calling code.
For parts of the question:
What part of a function makes it asynchronous?
Standard functions are not inherently asynchronous: it is how they are called that determines their synchronicity or otherwise. Describing a standard function as an "asynchronous function" would mean it is intended to be called asynchronously. Calling an async function an "asynchronous function" is a simplification: async functions are often called synchronously but always involve asynchronous code execution.
API functione like fetch() and addEventListener()
document.addEventListener("click", event=>console.log("clicked"))
adds the anonymous arrow function as a click event listener. Because the arrow function not called as part of the above script's execution flow, you can say it's called asynchronously when a user clicks the mouse.
Similar considerations apply to fetch: the code calling fetch returns to the event loop, the browser initiates a network request, waits for a response, places a task in a task queue and the event loop task manager calls the fetch callback with data. The callback runs asynchronously with respect to the code that called fetch in the first place.
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
A call to loadScript will execute the function's body code and synchronously return to the caller which continues execution after the call. It does however have side effects:
If loadScript is called while parsing HTML source, the absence of an async attribute on the script element means the HTML parser will stop parsing further HTML source until after the script has been fetched from the location specified in src, parsed by the JavaScript parser and executed. However execution of the loaded script is asynchronous: it only executes after the code calling loadScript returns to the event loop.
If the above code is executed after HTML parsing has reached end of input, the async attribute value is ignored and the script will be loaded asynchronously anyway. Placing "load" and "error" handlers on the script element allows obtaining notification of script load success or failure.

How browser api handles multiple asynchronous functions like setTimeOuts? [duplicate]

I am thinking about it and this is what I came up with:
Let's see this code below:
console.clear();
console.log("a");
setTimeout(function(){console.log("b");},1000);
console.log("c");
setTimeout(function(){console.log("d");},0);
A request comes in, and JS engine starts executing the code above step by step. The first two calls are sync calls. But when it comes to setTimeout method, it becomes an async execution. But JS immediately returns from it and continue executing, which is called Non-Blocking or Async. And it continues working on other etc.
The results of this execution is the following:
a c d b
So basically the second setTimeout got finished first and its callback function gets executed earlier than the first one and that makes sense.
We are talking about single-threaded application here. JS Engine keeps executing this and unless it finishes the first request, it won't go to second one. But the good thing is that it won't wait for blocking operations like setTimeout to resolve so it will be faster because it accepts the new incoming requests.
But my questions arise around the following items:
#1: If we are talking about a single-threaded application, then what mechanism processes setTimeouts while the JS engine accepts more requests and executes them? How does the single thread continue working on other requests? What works on setTimeout while other requests keep coming in and get executed.
#2: If these setTimeout functions get executed behind the scenes while more requests are coming in and being executed, what carries out the async executions behind the scenes? What is this thing that we talk about called the EventLoop?
#3: But shouldn't the whole method be put in the EventLoop so that the whole thing gets executed and the callback method gets called? This is what I understand when talking about callback functions:
function downloadFile(filePath, callback)
{
blah.downloadFile(filePath);
callback();
}
But in this case, how does the JS Engine know if it is an async function so that it can put the callback in the EventLoop? Perhaps something like the async keyword in C# or some sort of an attribute which indicates the method JS Engine will take on is an async method and should be treated accordingly.
#4: But an article says quite contrary to what I was guessing on how things might be working:
The Event Loop is a queue of callback functions. When an async
function executes, the callback function is pushed into the queue. The
JavaScript engine doesn't start processing the event loop until the
code after an async function has executed.
#5: And there is this image here which might be helpful but the first explanation in the image is saying exactly the same thing mentioned in question number 4:
So my question here is to get some clarifications about the items listed above?
1: If we are talking about a single-threaded application, then what processes setTimeouts while JS engine accepts more requests and executes them? Isn't that single thread will continue working on other requests? Then who is going to keep working on setTimeout while other requests keep coming and get executed.
There's only 1 thread in the node process that will actually execute your program's JavaScript. However, within node itself, there are actually several threads handling operation of the event loop mechanism, and this includes a pool of IO threads and a handful of others. The key is the number of these threads does not correspond to the number of concurrent connections being handled like they would in a thread-per-connection concurrency model.
Now about "executing setTimeouts", when you invoke setTimeout, all node does is basically update a data structure of functions to be executed at a time in the future. It basically has a bunch of queues of stuff that needs doing and every "tick" of the event loop it selects one, removes it from the queue, and runs it.
A key thing to understand is that node relies on the OS for most of the heavy lifting. So incoming network requests are actually tracked by the OS itself and when node is ready to handle one it just uses a system call to ask the OS for a network request with data ready to be processed. So much of the IO "work" node does is either "Hey OS, got a network connection with data ready to read?" or "Hey OS, any of my outstanding filesystem calls have data ready?". Based upon its internal algorithm and event loop engine design, node will select one "tick" of JavaScript to execute, run it, then repeat the process all over again. That's what is meant by the event loop. Node is basically at all times determining "what's the next little bit of JavaScript I should run?", then running it. This factors in which IO the OS has completed, and things that have been queued up in JavaScript via calls to setTimeout or process.nextTick.
2: If these setTimeout will get executed behind the scenes while more requests are coming and in and being executed, the thing carry out the async executions behind the scenes is that the one we are talking about EventLoop?
No JavaScript gets executed behind the scenes. All the JavaScript in your program runs front and center, one at a time. What happens behind the scenes is the OS handles IO and node waits for that to be ready and node manages its queue of javascript waiting to execute.
3: How can JS Engine know if it is an async function so that it can put it in the EventLoop?
There is a fixed set of functions in node core that are async because they make system calls and node knows which these are because they have to call the OS or C++. Basically all network and filesystem IO as well as child process interactions will be asynchronous and the ONLY way JavaScript can get node to run something asynchronously is by invoking one of the async functions provided by the node core library. Even if you are using an npm package that defines it's own API, in order to yield the event loop, eventually that npm package's code will call one of node core's async functions and that's when node knows the tick is complete and it can start the event loop algorithm again.
4 The Event Loop is a queue of callback functions. When an async function executes, the callback function is pushed into the queue. The JavaScript engine doesn't start processing the event loop until the code after an async function has executed.
Yes, this is true, but it's misleading. The key thing is the normal pattern is:
//Let's say this code is running in tick 1
fs.readFile("/home/barney/colors.txt", function (error, data) {
//The code inside this callback function will absolutely NOT run in tick 1
//It will run in some tick >= 2
});
//This code will absolutely also run in tick 1
//HOWEVER, typically there's not much else to do here,
//so at some point soon after queueing up some async IO, this tick
//will have nothing useful to do so it will just end because the IO result
//is necessary before anything useful can be done
So yes, you could totally block the event loop by just counting Fibonacci numbers synchronously all in memory all in the same tick, and yes that would totally freeze up your program. It's cooperative concurrency. Every tick of JavaScript must yield the event loop within some reasonable amount of time or the overall architecture fails.
Don't think the host process to be single-threaded, they are not. What is single-threaded is the portion of the host process that execute your javascript code.
Except for background workers, but these complicate the scenario...
So, all your js code run in the same thread, and there's no possibility that you get two different portions of your js code to run concurrently (so, you get not concurrency nigthmare to manage).
The js code that is executing is the last code that the host process picked up from the event loop.
In your code you can basically do two things: run synchronous instructions, and schedule functions to be executed in future, when some events happens.
Here is my mental representation (beware: it's just that, I don't know the browser implementation details!) of your example code:
console.clear(); //exec sync
console.log("a"); //exec sync
setTimeout( //schedule inAWhile to be executed at now +1 s
function inAWhile(){
console.log("b");
},1000);
console.log("c"); //exec sync
setTimeout(
function justNow(){ //schedule justNow to be executed just now
console.log("d");
},0);
While your code is running, another thread in the host process keep track of all system events that are occurring (clicks on UI, files read, networks packets received etc.)
When your code completes, it is removed from the event loop, and the host process return to checking it, to see if there are more code to run. The event loop contains two event handler more: one to be executed now (the justNow function), and another within a second (the inAWhile function).
The host process now try to match all events happened to see if there handlers registered for them.
It found that the event that justNow is waiting for has happened, so it start to run its code. When justNow function exit, it check the event loop another time, searhcing for handlers on events. Supposing that 1 s has passed, it run the inAWhile function, and so on....
The Event Loop has one simple job - to monitor the Call Stack, the Callback Queue and Micro task queue. If the Call Stack is empty, the Event Loop will take the first event from the micro task queue then from the callback queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop.
As most developers know, that Javascript is single threaded, means two statements in javascript can not be executed in parallel which is correct. Execution happens line by line, which means each javascript statements are synchronous and blocking. But there is a way to run your code asynchronously, if you use setTimeout() function, a Web API given by the browser, which makes sure that your code executes after specified time (in millisecond).
Example:
console.log("Start");
setTimeout(function cbT(){
console.log("Set time out");
},5000);
fetch("http://developerstips.com/").then(function cbF(){
console.log("Call back from developerstips");
});
// Millions of line code
// for example it will take 10000 millisecond to execute
console.log("End");
setTimeout takes a callback function as first parameter, and time in millisecond as second parameter.
After the execution of above statement in browser console it will print
Start
End
Call back from developerstips
Set time out
Note: Your asynchronous code runs after all the synchronous code is done executing.
Understand How the code execution line by line
JS engine execute the 1st line and will print "Start" in console
In the 2nd line it sees the setTimeout function named cbT, and JS engine pushes the cbT function to callBack queue.
After this the pointer will directly jump to line no.7 and there it will see promise and JS engine push the cbF function to microtask queue.
Then it will execute Millions of line code and end it will print "End"
After the main thread end of execution the event loop will first check the micro task queue and then call back queue. In our case it takes cbF function from the micro task queue and pushes it into the call stack then it will pick cbT funcion from the call back queue and push into the call stack.
JavaScript is high-level, single-threaded language, interpreted language. This means that it needs an interpreter which converts the JS code to a machine code. interpreter means engine. V8 engines for chrome and webkit for safari. Every engine contains memory, call stack, event loop, timer, web API, events, etc.
Event loop: microtasks and macrotasks
The event loop concept is very simple. There’s an endless loop, where the JavaScript engine waits for tasks, executes them and then sleeps, waiting for more tasks
Tasks are set – the engine handles them – then waits for more tasks (while sleeping and consuming close to zero CPU). It may happen that a task comes while the engine is busy, then it’s enqueued. The tasks form a queue, so-called “macrotask queue”
Microtasks come solely from our code. They are usually created by promises: an execution of .then/catch/finally handler becomes a microtask. Microtasks are used “under the cover” of await as well, as it’s another form of promise handling. Immediately after every macrotask, the engine executes all tasks from microtask queue, prior to running any other macrotasks or rendering or anything else.

Why do callbacks functions allow us to do things asynchronously in Javascript?

I've read that callbacks make JavaScript asynchronously. But I'm not sure if I understood the explanation. This is what I get
Callback functions allow us to do things asynchronously, since they ensure
that the lines prior to the callback are completely finished before loading
the next line.
Is that true? Thanks
First off, it isn't the callback that enables anything. A given operation in node.js or even browser-based javascript either is or isn't asynchronous. It really has nothing to do with the callback, though a callback is typically used to communicate results of an asynchronous operation.
For example, Javascript's array.forEach() uses a callback, but it is not asynchronous. So, async operations are async because their underlying implementation is non-blocking. You start the operation by making a function call, the operation proceeds in the background and the rest of your code continues to run. Meanwhile, when the asynchronous operation completes, it usually then needs to tell your code that it is done and perhaps communicate some results. A callback function is the chosen mechanism for communicating the completion of the async operation.
I've read that callbacks make JavaScript asynchronously.
No, that is not really true. Callbacks can be used with synchronous operations too. Just because one uses a callback does not make anything asynchronous. The underlying native code implementation of an operation must be asynchronous (such as an Ajax call or other networking operation). Callbacks are used to communicate the results of asynchronous operations. They are also have many other non-asynchronous uses too. So, a callback is just one tool used in an asynchronous operation and a callback is a tool with many other uses too. You cannot say callback === asynchronous.
Callback functions allow us to do things asynchronously, since they
ensure that the lines prior to the callback are completely finished
before loading the next line.
It is hard to tell exactly what you mean by this, but it sounds wrong to me. When using asynchronous operations, code is typically not executed in the order laid out in the file. For example, if you did this:
console.log("async start");
callSomeAsyncOperation(function(result) {
console.log("async done");
});
console.log("I'm here now");
You would see this in the log:
async start
I'm here now
async done
Callbacks and Event Queues Explained
It may also be useful to understand how an asynchronous operation works. Javascript works off an event queue. A given sequence of Javascript code runs to its completion. When that completes, the engine looks in the event queue to see if there are any more events to process. If so, the first event in the queue is pulled out and a callback that was registered for that event is called. This starts a new sequence of Javascript code running. That code continues to run until it finishes. When it finishes, the engine checks for another event. If there is one, it is then processed by calling a callback associated with that event. When there are no more events to process, the engine goes to sleep waiting for the next event. When an event occurs (outside the main Javascript thead), it is then added to the queue and that process of adding it to the queue causes the JS engine to wake up and service that event.
When writing your Javascript, you will often register and event handler for an event. The way this works in Javascript is that you say what event you're interested in (which may also include specifying some other information like what object you're looking for events on) and then you pass it is a function reference. You are, in essence, telling the Javascript engine that you want it to call your function reference when this event occurs. This type of function reference is referred to as a "callback". It's just a normal function, but the context in which it is being used is called a "callback" because some other code will "call you back" at some time in the future by executing your function. You can then place appropriate code in that function reference (inside that callback function) that can respond to that event. Depending upon the type of event, you may only get called once or it may call you every time that event occurs.
You can read more about how this event queue and callbacks work in these references:
Run Arbitrary Code While Waiting For Callback in Node?
blocking code in non-blocking http server
Hidden threads in Javascript/Node that never execute user code: is it possible, and if so could it lead to an arcane possibility for a race condition?
How does JavaScript handle AJAX responses in the background? (written about the browser, but concept is the same)
First of all, let's understand what callback is (by definition):
In computer programming, a callback is a piece of executable code that
is passed as an argument to other code, which is expected to call back
(execute) the argument at some convenient time. The invocation may be
immediate as in a synchronous callback, or it might happen at later
time as in an asynchronous callback. In all cases, the intention is to
specify a function or subroutine as an entity that is, depending on
the language, more or less similar to a variable.
Now, talking about Javascript, not always a callback is asynchronous. For example:
function syncOperation(callback) {
callback();
}
syncOperation(function() {
console.log('a');
console.log('b');
});
console.log('c');
That callback is synchronous, since it doesn't make any asynchronous operation. If you open your console and run the code above, you'll see that it will log a, then b, then c.
Now, let's see an asynchronous example:
function asyncOperation(callback) {
setTimeout(callback, 0);
}
asyncOperation(function() {
console.log('a');
console.log('b');
});
console.log('c');
You'll see firstly c, then a, and b. That's because the setTimeout function runs asynchronously.
Some built-in Javascript functions are asynchronous, and they will run, and at some time, they will call the function you passed as parameter back. That's why if you do:
var a = 'text';
setTimeout(function() { a = 'new text'; }, 0);
console.log(a);
You'll see in your console text, because it will run before the variable has been changed.

Are JavaScript functions asynchronous?

Consider the following function being executed,
function loadPage()
{
takeInput();
processInput();
outputInput();
}
In what order would they be executed(I have read that it follows stack so option 2 will be the answer)?
Option #1
takeInput();
processInput();
outputInput();
Option #2
outputInput();
processInput();
takeInput();
JavaScript functions are not asynchronous. Some very limited set of functions have an asynchronous API:
addEventListener, setTimeout, setInterval. These are the only 3 (which I thought was very surprising).
They allow you to pass in a callback that may get called eventually. Such as when a timer expires, or when a user clicks on something, or when an AJAX request completes.
JavaScript has an event loop. The event loop processes each event as it comes in. If you click a button 3 times and then a timer expires that will also be the order the events are handled. It is all very well defined and determined.
Furthermore, JavaScript doesn't have threads, it runs one event completely till there is nothing left to do (you return) before starting the next event. So events will never interfere in any way. This allows you to make very strong assumptions about the state of your data.
Are JavaScript functions asynchronous?
Some are, most are not.
In what order would they be executed
They will be executed in the order in which they are called. Since they are are all called from the same function, that will be in a simple linear order.
If any of them are written in an asynchronous way, then they might not finish all their activity in the same order. For example:
function a() {
console.log('a');
}
function b() {
console.log('b');
}
function c() {
console.log('c');
}
function aAsync() {
setTimeout(a, 500);
}
function load() {
aAsync();
b();
c();
}
load();
Javascript is not Asynchronous. It works Synchronously ,that is it runs one line of code at a time.
When javascript code is run , first a Global execution context is created and if you call a function from global execution context, another execution context is created by the javascript engine and that is placed at the top of the execution stack (global execution context is already in the stack)and if there is another function being called from inside that function ,another execution context is created and stack size keeps on increasing.
So,javascript engine keeps running this code one line at a time and in that process if there is any event/ http request fires, the browser puts them in the EVENT QUEUE. So, the point is javascript engine wont process the events in queue until the execution stack is empty.
And when the engine is done with the execution stack, it periodically looks if there is any event handler for current event in queue and similarly creates execution context for that handler and runs the code within.
So, the whole process is just synchronous and asynchronousity is just handled by the other parts of browser like(rendering engine or http engine) while the javascript engine continues to run the code synchronously.
So, in your case,
from whichever context function loadpage was invoked , its execution context was created and and placed at the top of the stack. Then, it invokes the takeinput function, its exec. context is created and and other functions context will not be created and placed in the stack until the takeinput context is popped out from the execution stack.
So, the correct order will be takeinput, processinput and outputinput.
I hope it answers your question.
JavaScript is not, generally asynchronous, but it does have asynchronous and event driven methods.
Ajax calls are the big asynchronous methods.
For events, I'm not sure that you can be guaranteed about an order of execution, but I might be wrong about that.
No, not by default/as standard, though there are asynchronous methods. And jQuery makes use of asynchronous behaviour much more so. But in each case, it's subjective, and can't be said that "All of the JavaScript is this or that".
Methods are always executed in the order they are called; the asynchronousness of them means that any may complete before another, even if called afterwards.
Javascript is a single-threaded beast, so strictly speaking tasks are not asynchronous as one might think of in terms of spawning child threads to execute code. The mechanisms that provide this create the illusion of asynchronicity, but its still single-threaded.

Categories

Resources