Run Async Function Again After It Returns Python
Let me start this article by asking, "What is JavaScript"? Well, here's the almost confusing withal to-the-betoken respond I take found so far:
JavaScript is a single-threaded, non-blocking, asynchronous, concurrent programming language with lots of flexibility.
Concur on a second – did it say single-threaded and asynchronous at the aforementioned time? If you understand what unmarried-threaded means, you lot'll likely generally associate it with synchronous operations. How can JavaScript exist asynchronous, then?
In this article, we will learn all about the synchronous and asynchronous parts of JavaScript. You apply both in spider web programming almost daily.
If you similar to learn from video content as well, this article is also available as a video tutorial here: 🙂
In this article, You'll Learn:
- How JavaScript is synchronous.
- How asynchronous operations occur when JavaScript is single-threaded.
- How agreement synchronous vs. asynchronous helps you ameliorate sympathize JavaScript promises.
- Lots of simple but powerful examples to cover these concepts in detail.
JavaScript Functions are First-Class Citizens
In JavaScript, you can create and modify a office, apply it as an argument, return it from some other office, and assign it to a variable. All these abilities allow us to use functions everywhere to place a bunch of code logically.
We need to tell the JavaScript engine to execute functions by invoking them. It'll wait similar this:
// Define a function office f1() { // Do something // Do something once more // Again // So on... } // Invoke the role f1(); By default, every line in a part executes sequentially, 1 line at a time. The aforementioned is applicative fifty-fifty when you invoke multiple functions in your lawmaking. Again, line by line.
Synchronous JavaScript – How the Function Execution Stack Works
And so what happens when you define a function and so invoke it? The JavaScript engine maintains a stack data structure chosen function execution stack. The purpose of the stack is to track the electric current function in execution. It does the following:
- When the JavaScript engine invokes a part, it adds it to the stack, and the execution starts.
- If the currently executed function calls some other function, the engine adds the second function to the stack and starts executing it.
- Once information technology finishes executing the 2nd function, the engine takes it out from the stack.
- The command goes back to resume the execution of the first function from the signal it left information technology last fourth dimension.
- One time the execution of the first function is over, the engine takes information technology out of the stack.
- Keep the aforementioned mode until in that location is nothing to put into the stack.
The function execution stack is likewise known every bit the Call Stack.
Let's look at an instance of three functions that execute one by one:
function f1() { // some code } function f2() { // some lawmaking } part f3() { // some code } // Invoke the functions one by one f1(); f2(); f3(); Now permit's see what happens with the role execution stack:
Did you run into what happened there? First, f1() goes into the stack, executes, and pops out. And then f2() does the same, and finally f3(). After that, the stack is empty, with zero else to execute.
Ok, let's now work through a more complex example. Hither is a role f3() that invokes another part f2() that in plough invokes another function f1().
function f1() { // Some code } office f2() { f1(); } function f3() { f2(); } f3(); Let's see what'southward going on with the function execution stack:
Notice that offset f3() gets into the stack, invoking some other part, f2(). And so at present f2() gets inside while f3() remains in the stack. The f2() function invokes f1(). Then, time for f1() to get within the stack with both f2() and f3() remaining inside.
First, f1() finishes executing and comes out of the stack. Correct after that f2() finishes, and finally f3().
The bottom line is that everything that happens inside the role execution stack is sequential. This is the Synchronous function of JavaScript. JavaScript's main thread makes certain that information technology takes care of everything in the stack before it starts looking into anything elsewhere.
Great! Now that we empathize how synchronous operations piece of work in JavaScript, let's now flip the money and run into its asynchronous side. Are you set up?
Asynchronous JavaScript – How Browser APIs and Promises Piece of work
The word asynchronous means not occurring at the same time. What does it mean in the context of JavaScript?
Typically, executing things in sequence works well. But you may sometimes need to fetch data from the server or execute a function with a delay, something you do not conceptualize occurring NOW. Then, you desire the code to execute asynchronously.
In these circumstances, yous may non want the JavaScript engine to halt the execution of the other sequential code. Then, the JavaScript engine needs to manage things a bit more efficiently in this case.
Nosotros can classify nigh asynchronous JavaScript operations with two primary triggers:
- Browser API/Spider web API events or functions. These include methods like
setTimeout, or event handlers like click, mouse over, scroll, and many more. - Promises. A unique JavaScript object that allows u.s.a. to perform asynchronous operations.
Don't worry if you are new to promises. You do non demand to know more than this to follow this commodity. At the cease of the article, I have provided some links then yous tin can start learning promises in the most beginner-friendly way.
How to Handle Browser APIs/Spider web APIs
Browser APIs like setTimeout and consequence handlers rely on callback functions. A callback function executes when an asynchronous operation completes. Here is an case of how a setTimeout office works:
role printMe() { panel.log('print me'); } setTimeout(printMe, 2000); The setTimeout function executes a function after a certain corporeality of time has elapsed. In the code higher up, the text print me logs into the console after a delay of 2 seconds.
Now assume we have a few more lines of lawmaking right later the setTimeout office similar this:
function printMe() { console.log('impress me'); } function test() { console.log('test'); } setTimeout(printMe, 2000); test(); So, what do nosotros await to happen here? What do you retrieve the output volition exist?
Volition the JavaScript engine wait for ii seconds to go to the invocation of the test() role and output this:
printMe examination Or volition it manage to proceed the callback office of setTimeout aside and go on its other executions? So the output could exist this, possibly:
exam printMe If you guessed the latter, y'all're right. That's where the asynchronous machinery kicks in.
How the JavaScript Callback Queue Works (aka Task Queue)
JavaScript maintains a queue of callback functions. It is chosen a callback queue or task queue. A queue information structure is Kickoff-In-First-Out(FIFO). So, the callback function that first gets into the queue has the opportunity to become out first. But the question is:
- When does the JavaScript engine put information technology in the queue?
- When does the JavaScript engine take information technology out of the queue?
- Where does it go when information technology comes out of the queue?
- Most importantly, how do all these things chronicle to the asynchronous function of JavaScript?
Whoa, lots of questions! Let's figure out the answers with the help of the following paradigm:
The above image shows the regular call stack we have seen already. There are two additional sections to track if a browser API (similar setTimeout) kicks in and queues the callback role from that API.
The JavaScript engine keeps executing the functions in the call stack. Every bit it doesn't put the callback function straight into the stack, there is no question of any code waiting for/blocking execution in the stack.
The engine creates a loop to wait into the queue periodically to find what it needs to pull from there. It pulls a callback function from the queue to the call stack when the stack is empty. Now the callback function executes generally as any other function in the stack. The loop continues. This loop is famously known equally the Event Loop.
So, the moral of the story is:
- When a Browser API occurs, park the callback functions in a queue.
- Proceed executing lawmaking equally usual in the stack.
- The event loop checks if there is a callback function in the queue.
- If so, pull the callback function from the queue to the stack and execute.
- Continue the loop.
Alright, let's come across how it works with the code below:
function f1() { console.log('f1'); } function f2() { console.log('f2'); } function chief() { panel.log('primary'); setTimeout(f1, 0); f2(); } master(); The code executes a setTimeout function with a callback function f1(). Note that we take given zero delays to it. This means that we wait the function f1() to execute immediately. Right later on setTimeout, we execute another function, f2().
So, what do you lot think the output will be? Here information technology is:
chief f2 f1 Simply, you may recollect that f1 should print before f2 as we exercise not delay f1 to execute. But no, that'due south not the case. Remember the event loop mechanism nosotros discussed to a higher place? Now, let'southward see it in a stride-past-step menses for the above code.
Here are steps written out:
- The
main()role gets inside the telephone call stack. - It has a console log to print the word primary. The
console.log('primary')executes and goes out of the stack. - The setTimeout browser API takes identify.
- The callback function puts it into the callback queue.
- In the stack, execution occurs as usual, so
f2()gets into the stack. The panel log off2()executes. Both leave of the stack. - The
chief()also pops out of the stack. - The event loop recognizes that the call stack is empty, and there is a callback function in the queue.
- The callback function
f1()then goes into the stack. Execution starts. The console log executes, andf1()also comes out of the stack. - At this point, nothing else is in the stack and queue to execute further.
I hope it's now clear to yous how the asynchronous function of JavaScript works internally. Just, that's non all. We take to look at promises.
How the JavaScript Engine Handles Promises
In JavaScript, promises are special objects that help you perform asynchronous operations.
Yous tin create a hope using the Promise constructor. You need to pass an executor function to it. In the executor function, you define what you want to do when a promise returns successfully or when it throws an error. You can practise that past calling the resolve and pass up methods, respectively.
Here is an example of a promise in JavaScript:
const promise = new Promise((resolve, reject) => resolve('I am a resolved promise'); ); After the hope is executed, nosotros tin can handle the result using the .then() method and any errors with the .catch() method.
hope.then(effect => console.log(outcome)) You utilise promises every fourth dimension you use the fetch() method to become some data from a shop.
The point hither is that JavaScript engine doesn't use the aforementioned callback queue nosotros take seen before for browser APIs. It uses some other special queue called the Job Queue.
What is the Chore Queue in JavaScript?
Every time a promise occurs in the lawmaking, the executor role gets into the job queue. The consequence loop works, as usual, to look into the queues but gives priority to the job queue items over the callback queue items when the stack is free.
The item in the callback queue is called a macro job, whereas the item in the job queue is called a micro job.
And then the unabridged flow goes like this:
- For each loop of the
event loop, ane chore is completed out of thecallback queue. - Once that task is complete, the issue loop visits the
task queue. It completes all themicro tasksin the task queue before it looks into the adjacent thing. - If both the queues got entries at the same point in fourth dimension, the
job queuegets preference over thecallback queue.
The paradigm beneath shows the inclusion of the chore queue forth with other preexisting items.
Now, let's await at an instance to sympathise this sequence meliorate:
function f1() { console.log('f1'); } function f2() { console.log('f2'); } function primary() { panel.log('main'); setTimeout(f1, 0); new Promise((resolve, pass up) => resolve('I am a promise') ).so(resolve => panel.log(resolve)) f2(); } main(); In the above code, we take a setTimeout() function as before, but we have introduced a promise right after it. Now remember all that we take learned and estimate the output.
If your answer matches this, you are correct:
main f2 I am a hope f1 Now let's see the flow of actions:
The flow is well-nigh the same as above, but it is crucial to discover how the items from the job queue prioritize the items from the task queue. Also note that it doesn't fifty-fifty matter if the setTimeout has cipher delay. It is always about the job queue that comes before the callback queue.
Alright, we have learned everything we need to understand synchronous and asynchronous execution in JavaScript.
Here is a Quiz for You!
Let's test your understanding past taking a quiz. Estimate the output of the post-obit code and apply all the cognition we have gained then far:
role f1() { console.log('f1'); } role f2() { panel.log('f2'); } function f3() { console.log('f3'); } part main() { console.log('main'); setTimeout(f1, fifty); setTimeout(f3, thirty); new Promise((resolve, refuse) => resolve('I am a Promise, right later f1 and f3! Actually?') ).so(resolve => console.log(resolve)); new Promise((resolve, turn down) => resolve('I am a Promise after Promise!') ).then(resolve => console.log(resolve)); f2(); } primary(); Here is the expected output:
master f2 I am a Hope, right later on f1 and f3! Actually? I am a Promise afterward Promise! f3 f1 Do yous desire more such quizzes? Head over to this repository to practice more exercises.
In example y'all are stuck or need any clarifications, my DM is ever open on Twitter.
In Summary
To summarize:
- The JavaScript engine uses the stack data construction to keep runway of currently executed functions. The stack is called the function execution stack.
- The part execution stack (aka telephone call stack) executes the functions sequentially, line-past-line, one-by-one.
- The browser/spider web APIs use callback functions to complete the tasks when an asynchronous operation/delay is done. The callback function is placed in the callback queue.
- The promise executor functions are placed in the job queue.
- For each loop of the event loop, one macro task is completed out of the callback queue.
- Once that task is complete, the event loop visits the job queue. It completes all the micro-tasks in the task queue before it looks for the next matter.
- If both the queues get entries at the same point in time, the task queue gets preference over the callback queue.
Earlier We End...
That'southward all for now. I hope y'all've institute this article insightful, and that it helps yous understand JavaScript'due south synchronous vs asynchronous concepts better.
Allow's connect. You can follow me on Twitter(@tapasadhikary), My Youtube channel, and GitHub(atapas).
Every bit promised before, here are a few articles yous may find useful,
- JavaScript Promises - Explicate Similar I'one thousand Five
- JavaScript Promise Chain - The art of handling promises
- JavaScript async and expect - in plain English, please
- Introducing PromiViz - visualize and acquire JavaScript hope APIs
Learn to code for costless. freeCodeCamp'southward open source curriculum has helped more than than 40,000 people become jobs as developers. Become started
Source: https://www.freecodecamp.org/news/synchronous-vs-asynchronous-in-javascript/
0 Response to "Run Async Function Again After It Returns Python"
Post a Comment