How To Forcefully Make Angularjs Code To Wait Untill Service Call Is Executed

When does an asynchronous role cease? And why is this such a hard question to reply?
Well it turns out that understanding asynchronous functions requires a great bargain of knowledge about how JavaScript works fundamentally.
Let'south go explore this concept, and learn a lot about JavaScript in the process.
Are you ready? Allow's go.
What is asynchronous code?
Past design, JavaScript is a synchronous programming language. This means that when lawmaking is executed, JavaScript starts at the top of the file and runs through code line by line, until it is washed.
The result of this design conclusion is that simply 1 thing can happen at any one time.
You tin retrieve of this equally if you were juggling vi small balls. While you lot are juggling, your hands are occupied and can't handle anything else.
It's the same with JavaScript: one time the lawmaking is running, it has its hands full with that lawmaking. We call this this kind of synchronous code blocking. Because it's effectively blocking other code from running.
Let's circle back to the juggling example. What would happen if you wanted to add another ball? Instead of six balls, you lot wanted to juggle seven assurance. That'south might exist a problem.
You don't want to cease juggling, because information technology's just so much fun. Just you can't become and become another ball either, because that would mean you'd have to stop.
The solution? Delegate the work to a friend or family unit member. They aren't juggling, and then they can go and get the ball for you lot, then toss it into your juggling at a time when your hand is free and y'all are ready to add together another brawl mid-juggle.
This is what asynchronous lawmaking is. JavaScript is delegating the piece of work to something else, then going about information technology's ain business organisation. So when information technology's ready, information technology will receive the results back from the piece of work.
Who is doing the other work?
Alright, so we know that JavaScript is synchronous and lazy. It doesn't want to do all of the piece of work itself, so it farms it out to something else.
Just who is this mysterious entity that works for JavaScript? And how does it become hired to work for JavaScript?
Well, let'southward accept a wait at an example of asynchronous code.
const logName = () => { panel.log("Han") } setTimeout(logName, 0) console.log("Hi there")
Running this code results in the following output in the console:
// in console How-do-you-do there Han
Alright. What is going on?
It turns out that the manner we subcontract out work in JavaScript is to use environment-specific functions and APIs. And this is a source of groovy defoliation in JavaScript.
JavaScript e'er runs in an environment.
Oftentimes, that environment is the browser. Merely it can also be on the server with NodeJS. But what on globe is the deviation?
The difference – and this is important – is that the browser and the server (NodeJS), functionality-wise, are not equivalent. They are often like, simply they are non the same.
Let's illustrate this with an case. Allow's say JavaScript is the protagonist of an epic fantasy book. Simply an ordinary farm child.
Now let's say that this subcontract child establish two suits of special armor that gave them powers beyond their ain.
When they used the browser adjust of armor, they gained access to a certain gear up of capabilities.
When they used the server conform of armor they gained access to some other prepare of capabilities.
These suits accept some overlap, considering the creators of these suits had the same needs in sure places, but not in others.
This is what an surround is. A identify where code is run, where there be tools that are built on peak of the existing JavaScript language. They are not a office of the language, simply the line is frequently blurred because nosotros use these tools every day when we write lawmaking.
setTimeout, fetch, and DOM are all examples of Web APIs. (You can see the full list of Web APIs here.) They are tools that are built into the browser, and that are made available to us when our lawmaking is run.
And because we ever run JavaScript in an environment, it seems like these are part of the linguistic communication. Only they are not.
Then if you've ever wondered why y'all tin use fetch in JavaScript when you run it in the browser (simply demand to install a package when you lot run information technology in NodeJS), this is why. Someone thought fetch was a skilful idea, and built information technology as a tool for the NodeJS surroundings.
Disruptive? Yeah!
Just now we can finally understand what takes on the work from JavaScript, and how it gets hired.
Information technology turns out that it is the environment that takes on the work, and the manner to get the environment to do that work, is to use functionality that belongs to the environment. For example fetch or setTimeout in the browser surroundings.
What happens to the work?
Great. And so the environment takes on the piece of work. Then what?
At some betoken you need to go the results back. Just let'southward think about how this would work.
Allow's get back to the juggling example from the beginning. Imagine yous asked for a new ball, and a friend just started throwing the brawl at y'all when you lot weren't ready.
That would be a disaster. Maybe you lot could become lucky and catch information technology and get it into your routine effectively. But theres a large risk that it may cause y'all to drop all of your balls and crash your routine. Wouldn't it exist improve if you gave strict instructions on when to receive the brawl?
As it turns out, there are strict rules surrounding when JavaScript can receive delegated piece of work.
Those rules are governed by the event loop and involve the microtask and macrotask queue. Yeah, I know. It's a lot. Merely bear with me.

Alright. So when we consul asynchronous code to the browser, the browser takes and runs the code and takes on that workload. But there may be multiple tasks that are given to the browser, so we need to make sure that nosotros tin prioritise these tasks.
This is where the microtask queue and the macrotask queue come up in play. The browser will take the work, practise information technology, then identify the result in one of the two queues based on the type of work it receives.
Promises, for example, are placed in the microtask queue and have a higher priority.
Events and setTimeout are examples of work that is put in the macrotask queue, and have a lower priority.
Now in one case the work is done, and is placed in 1 of the two queues, the event loop will run dorsum and along and check whether or not JavaScript is fix to receive the results.
But when JavaScript is done running all its synchronous code, and is good and set, will the event loop start picking from the queues and handing the functions back to JavaScript to run.
And so let'south take a look at an example:
setTimeout(() => panel.log("hello"), 0) fetch("https://someapi/data").then(response => response.json()) .then(data => console.log(data)) console.log("What soup?")
What will the order be here?
- Firstly, setTimeout is delegated to the browser, which does the work and puts the resulting part in the macrotask queue.
- Secondly fetch is delegated to the browser, which takes the piece of work. It retrieves the data from the endpoint and puts the resulting functions in the microtask queue.
- Javascript logs out "What soup"?
- The event loop checks whether or not JavaScript is ready to receive the results from the queued work.
- When the console.log is done, JavaScript is ready. The issue loop picks queued functions from the microtask queue, which has a higher priority, and gives them back to JavaScript to execute.
- Later the microtask queue is empty, the setTimeout callback is taken out of the macrotask queue and given back to JavaScript to execute.
In console: // What soup? // the data from the api // hello
Promises
Now y'all should have a adept deal of knowledge about how asynchronous lawmaking is handled by JavaScript and the browser surroundings. So let'south talk about promises.
A hope is a JavaScript construct that represents a futurity unknown value. Conceptually, a promise is just JavaScript promising to return a value. It could be the issue from an API call, or it could be an error object from a failed network asking. You're guaranteed to go something.
const promise = new Promise((resolve, reject) => { // Make a network request if (response.status === 200) { resolve(response.body) } else { const error = { ... } turn down(mistake) } }) promise.then(res => { console.log(res) }).grab(err => { console.log(err) })
A promise can have the post-obit states:
- fulfilled - activeness successfully completed
- rejected - action failed
- pending - neither action has been completed
- settled - has been fulfilled or rejected
A promise receives a resolve and a reject function that can exist called to trigger one of these states.
One of the big selling points of promises is that we can chain functions that we want to happen on success (resolve) or failure (refuse):
- To annals a office to run on success we utilize .then
- To register a function to run on failure nosotros apply .catch
// Fetch returns a promise fetch("https://swapi.dev/api/people/one") .then((res) => console.log("This function is run when the request succeeds", res) .catch(err => panel.log("This function is run when the request fails", err) // Chaining multiple functions fetch("https://swapi.dev/api/people/1") .then((res) => doSomethingWithResult(res)) .then((finalResult) => panel.log(finalResult)) .take hold of((err => doSomethingWithErr(err))
Perfect. Now allow's take a closer look at what this looks similar under the hood, using fetch every bit an example:
const fetch = (url, options) => { // simplified return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest() // ... make request xhr.onload = () => { const options = { condition: xhr.status, statusText: xhr.statusText ... } resolve(new Response(xhr.response, options)) } xhr.onerror = () => { reject(new TypeError("Asking failed")) } } fetch("https://swapi.dev/api/people/one") // Register handleResponse to run when promise resolves .then(handleResponse) .catch(handleError) // conceptually, the promise looks similar this now: // { condition: "pending", onsuccess: [handleResponse], onfailure: [handleError] } const handleResponse = (response) => { // handleResponse volition automatically receive the response, ¨ // because the hope resolves with a value and automatically injects into the function console.log(response) } const handleError = (response) => { // handleError will automatically receive the mistake, ¨ // considering the promise resolves with a value and automatically injects into the office console.log(response) } // the hope will either resolve or reject causing information technology to run all of the registered functions in the respective arrays // injecting the value. Let's inspect the happy path: // 1. XHR event listener fires // 2. If the asking was successfull, the onload consequence listener triggers // 3. The onload fires the resolve(VALUE) function with given value // 4. Resolve triggers and schedules the functions registered with .so
So we can use promises to practise asynchronous work, and to be sure that we tin can handle any effect from those promises. That is the value proposition. If yous want to know more than most promises you tin read more than nearly them here and hither.
When nosotros use promises, we chain our functions onto the hope to handle the different scenarios.
This works, just nosotros still demand to handle our logic inside callbacks (nested functions) in one case nosotros get our results back. What if we could use promises but write synchronous looking code? It turns out we can.
Async/Await
Async/Await is a way of writing promises that allows us to write asynchronous code in a synchronous manner. Allow's have a look.
const getData = async () => { const response = await fetch("https://jsonplaceholder.typicode.com/todos/1") const data = wait response.json() console.log(data) } getData()
Goose egg has changed nether the hood here. We are notwithstanding using promises to fetch data, simply now it looks synchronous, and we no longer have .then and .grab blocks.
Async / Await is actually just syntactic saccharide providing a manner to create lawmaking that is easier to reason about, without changing the underlying dynamic.
Let's accept a await at how information technology works.
Async/Await lets u.s.a. use generators to break the execution of a function. When we are using async / await nosotros are not blocking because the function is yielding the control back over to the main programme.
Then when the promise resolves we are using the generator to yield control back to the asynchronous function with the value from the resolved promise.
Y'all can read more than here for a smashing overview of generators and asynchronous code.
In outcome, we can now write asynchronous code that looks like synchronous code. Which means that information technology is easier to reason well-nigh, and we tin apply synchronous tools for error handling such as endeavour / take hold of:
const getData = async () => { try { const response = look fetch("https://jsonplaceholder.typicode.com/todos/i") const data = await response.json() console.log(data) } catch (err) { panel.log(err) } } getData()
Alright. So how do nosotros use information technology? In society to use async / look nosotros need to prepend the function with async. This does non brand it an asynchronous function, it simply allows us to use await inside of it.
Failing to provide the async keyword volition result in a syntax error when trying to utilize look within a regular function.
const getData = async () => { panel.log("We tin use await in this part") }
Because of this, we tin can not use async / await on elevation level code. Just async and wait are however just syntactic sugar over promises. And so nosotros can handle top level cases with promise chaining:
async function getData() { let response = await fetch('http://apiurl.com'); } // getData is a hope getData().and so(res => console.log(res)).catch(err => panel.log(err);
This exposes another interesting fact nigh async / await. When defining a part as async, information technology volition always return a hope.
Using async / wait tin seem similar magic at first. But like any magic, it's just sufficiently advanced technology that has evolved over the years. Hopefully now you have a solid grasp of the fundamentals, and can utilize async / look with conviction.
Conclusion
If you fabricated it here, congrats. You only added a key piece of cognition nigh JavaScript and how it works with its environments to your toolbox.
This is definitely a confusing subject, and the lines are not ever clear. But now you hopefully have a grasp on how JavaScript works with asynchronous code in the browser, and a stronger grasp over both promises and async / wait.
If you enjoyed this article, you might as well enjoy my youtube channel. I currently take a web fundamentals series going where I go through HTTP, building spider web servers from scratch and more.
There's besides a series going on building an entire app with React, if that is your jam. And I plan to add together much more content hither in the future going in depth on JavaScript topics.
And if you desire to say hi or chat about web development, you could e'er accomplish out to me on twitter at @foseberg. Thank you for reading!
Learn to code for costless. freeCodeCamp's open source curriculum has helped more xl,000 people get jobs as developers. Get started
How To Forcefully Make Angularjs Code To Wait Untill Service Call Is Executed,
Source: https://www.freecodecamp.org/news/async-await-javascript-tutorial/
Posted by: matthiesaltrove88.blogspot.com
0 Response to "How To Forcefully Make Angularjs Code To Wait Untill Service Call Is Executed"
Post a Comment