Showing posts with label Js. Show all posts
Showing posts with label Js. Show all posts

Monday, July 19, 2021

What are Jobs in ES6

A new concept called the “Job Queue” was introduced in ES6. It’s a layer on top of the Event Loop queue. You are most likely to bump into it when dealing with the asynchronous behavior of Promises (we’ll talk about them too).

We’ll just touch on the concept now so that when we discuss async behavior with Promises, later on, you understand how those actions are being scheduled and processed.

Imagine it like this: the Job Queue is a queue that’s attached to the end of every tick in the Event Loop queue. Certain async actions that may occur during a tick of the event loop will not cause a whole new event to be added to the event loop queue, but will instead add an item (aka Job) to the end of the current tick’s Job queue.

This means that you can add another functionality to be executed later, and you can rest assured that it will be executed right after, before anything else.

A Job can also cause more Jobs to be added to the end of the same queue. In theory, it’s possible for a Job “loop” (a Job that keeps adding other Jobs, etc.) to spin indefinitely, thus starving the program of the necessary resources needed to move on to the next event loop tick. Conceptually, this would be similar to just expressing a long-running or infinite loop (like while (true) ..) in your code.

Jobs are kind of like the setTimeout(callback, 0) “hack” but implemented in such a way that they introduce a much more well-defined and guaranteed ordering: later, but as soon as possible.

Callbacks

As you already know, callbacks are by far the most common way to express and manage asynchronicity in JavaScript programs. Indeed, the callback is the most fundamental async pattern in the JavaScript language. Countless JS programs, even very sophisticated and complex ones, have been written on top of no other async foundation than the callback.

Except that callbacks don’t come with no shortcomings. Many developers are trying to find better async patterns. It’s impossible, however, to effectively use any abstraction if you don’t understand what’s actually under the hood.

In the following chapter, we’ll explore couple of these abstractions in-depth to show why more sophisticated async patterns (that will be discussed in subsequent posts) are necessary and even recommended.

Nested Callbacks

We’ve got a chain of three functions nested together, each one representing a step in an asynchronous series.

This kind of code is often called a “callback hell”. But the “callback hell” actually has almost nothing to do with the nesting/indentation. It’s a much deeper problem than that.

First, we’re waiting for the “click” event, then we’re waiting for the timer to fire, then we’re waiting for the Ajax response to come back, at which point it might get all repeated again.

At first glance, this code may seem to map its asynchrony naturally

So, such a sequential way of expressing your async code seems a lot more natural, doesn’t it? There must be such a way, right?

Promises

It’s all very straightforward: it sums the values of x and y and prints it to the console. What if, however, the value of x or was missing and was still to be determined? Say, we need to retrieve the values of both x and y from the server, before they can be used in the expression. Let’s imagine that we have a function loadX and loadY that respectively load the values of x and y from the server. Then, imagine that we have a function sum that sums the values of x and y once both of them are loaded.

There is something very important here — in that snippet, we treated x and y as future values, and we expressed an operation sum(…) that (from the outside) did not care whether x or y or both were or weren’t available right away.

Of course, this rough callbacks-based approach leaves much to be desired. It’s just a first tiny step towards understanding the benefits of reasoning about future values without worrying about the time aspect of when they will be available.

Promise Value

Let’s just briefly glimpse at how we can express the x + y example with Promises:

There are two layers of Promises in this snippet.

fetchX() and fetchY() are called directly, and the values they return (promises!) are passed to sum(...). The underlying values these promises represent may be ready now or later, but each promise normalizes its behavior to be the same regardless. We reason about x and y values in a time-independent way. They are future values, period.

The second layer is the promise that sum(...) creates
(via Promise.all([ ... ])) and returns, which we wait on by calling then(...). When the sum(...)operation completes, our sum future value is ready and we can print it out. We hide the logic for waiting on the x and y future values inside of sum(...) .

Note: Inside sum(…), the Promise.all([ … ]) call creates a promise (which is waiting on promiseX and promiseY to resolve). The chained call to .then(...) creates another promise, which the return
values[0] + values[1] line immediately resolves (with the result of the addition). Thus, the then(...) call we chain off the end of the sum(...) call — at the end of the snippet — is actually operating on that second promise returned, rather than the first one created by Promise.all([ ... ]). Also, although we are not chaining off the end of that second then(...), it too has created another promise, had we chosen to observe/use it. This Promise chaining stuff will be explained in much greater detail later in this chapter.

With Promises, the then(...) call can actually take two functions, the first for fulfillment (as shown earlier), and the second for rejection:

If something went wrong when getting x or y, or something somehow failed during the addition, the promise that sum(...) returns would be rejected, and the second callback error handler passed to then(...) would receive the rejection value from the promise.

Because Promises encapsulate the time-dependent state — waiting on the fulfillment or rejection of the underlying value — from the outside, the Promise itself is time-independent, and thus Promises can be composed (combined) in predictable ways regardless of the timing or outcome underneath.

Moreover, once a Promise is resolved, it stays that way forever — it becomes an immutable value at that point — and can then be observed as many times as necessary.

It’s really useful that you can actually chain promises:

Calling delay(2000) creates a promise that will fulfill in 2000ms, and then we return that from the first then(...) fulfillment callback, which causes the second then(...)'s promise to wait on that 2000ms promise.

Note: Because a Promise is externally immutable once resolved, it’s now safe to pass that value around to any party, knowing that it cannot be modified accidentally or maliciously. This is especially true in relation to multiple parties observing the resolution of a Promise. It’s not possible for one party to affect another party’s ability to observe Promise resolution. Immutability may sound like an academic topic, but it’s actually one of the most fundamental and important aspects of Promise design, and shouldn’t be casually passed over.

To Promise or not to Promise?

An important detail about Promises is knowing for sure if some value is an actual Promise or not. In other words, is it a value that will behave like a Promise?

We know that Promises are constructed by the new Promise(…) syntax, and you might think that p instanceof Promise would be a sufficient check. Well, not quite.

Mainly because you can receive a Promise value from another browser window (e.g. iframe), which would have its own Promise, different from the one in the current window or frame, and that check would fail to identify the Promise instance.

Moreover, a library or framework may choose to vend its own Promises and not use the native ES6 Promise implementation to do so. In fact, you may very well be using Promises with libraries in older browsers that have no Promise at all.

Swallowing exceptions

If at any point in the creation of a Promise, or in the observation of its resolution, a JavaScript exception error occurs, such as a TypeError or ReferenceError, that exception will be caught, and it will force the Promise in question to become rejected.


But what happens if a Promise is fulfilled yet there was a JS exception error during the observation (in a then(…) registered callback)? Even though it won’t be lost, you may find the way they’re handled a bit surprising. Until you dig a little deeper:

It looks like the exception from foo.bar() really did get swallowed. It wasn’t, though. There was something deeper that went wrong, however, which we failed to listen for. The p.then(…) call itself returns another promise, and it’s that promise that will be rejected with the TypeError exception.

Handling uncaught exceptions

There are other approaches which many would say are better.

A common suggestion is that Promises should have a done(…) added to them, which essentially marks the Promise chain as “done.” done(…)doesn’t create and return a Promise, so the callbacks passed to done(..) are obviously not wired up to report problems to a chained Promise that doesn’t exist.

It’s treated as you might usually expect in uncaught error conditions: any exception inside a done(..) rejection handler would be thrown as a global uncaught error (in the developer console, basically):

How JavaScript works: Event loop and the rise of Async programming

 What is the Event Loop?

We’ll start with a somewhat of an odd claim — despite allowing async JavaScript code (like the setTimeout), until ES6, JavaScript itself has actually never had any direct notion of asynchronicity built into it. The JavaScript engine has never done anything more than executing a single chunk of your program at any given moment.

For more details on how JavaScript engines work (Google’s V8 specifically).





So, who tells the JS Engine to execute chunks of your program? In reality, the JS Engine doesn’t run in isolation — it runs inside a hosting environment, which for most developers is the typical web browser or Node.js. Actually, nowadays, JavaScript gets embedded into all kinds of devices, from robots to light bulbs. Every single device represents a different type of hosting environment for the JS Engine.

The common denominator in all environments is a built-in mechanism called the event loop, which handles the execution of multiple chunks of your program over time, each time invoking the JS Engine.

This means that the JS Engine is just an on-demand execution environment for any arbitrary JS code. It’s the surrounding environment that schedules the events (the JS code executions).

So, for example, when your JavaScript program makes an Ajax request to fetch some data from the server, you set up the “response” code in a function (the “callback”), and the JS Engine tells the hosting environment:
“Hey, I’m going to suspend execution for now, but whenever you finish with that network request, and you have some data, please call this function back.”

The browser is then set up to listen for the response from the network, and when it has something to return to you, it will schedule the callback function to be executed by inserting it into the event loop.

Tuesday, February 19, 2019

Angular CLI cheat sheet

Install Globally

npm install -g @angular/cli

Install Locally

npm install @angular/cli
To run a locally installed version of the angular-cli, you can call ng commands directly by adding the .bin folder within your local node_modules folder to your PATH. The node_modules and .bin folders are created in the directory where npm install @angular/cli was run upon completion of the install command.
Alternatively, you can install npx and run npx ng <command> within the local directory where npm install @angular/cli
 was run, which will use the locally installed angular-cli.

Install Specific Version (Example: 6.1.1)

npm install -g @angular/cli@6.1.1

Usage

ng help

Generating and serving an Angular project via a development server

ng new PROJECT-NAME
cd PROJECT-NAME
ng serve
Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.
You can configure the default HTTP host and port used by the development server with two command-line options :
ng serve --host 0.0.0.0 --port 4201

Generating Components, Directives, Pipes and Services

You can use the ng generate (or just ng g) command to generate Angular components:
ng generate component my-new-component
ng g component my-new-component # using the alias 
 
# components support relative path generation 
# if in the directory src/app/feature/ and you run 
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp 
# but if you were to run 
ng g component ./newer-cmp
# your component will be generated in src/app/newer-cmp 
# if in the directory src/app you can also run 
ng g component feature/new-cmp
# and your component will be generated in src/app/feature/new-cmp 
You can find all possible blueprints in the table below:

Scaffold
Usage
ng g component my-new-component
ng g directive my-new-directive
ng g pipe my-new-pipe
ng g service my-new-service
ng g class my-new-class
ng g guard my-new-guard
ng g interface my-new-interface
ng g enum my-new-enum
ng g module my-module
1.      ng g module new-module to create a new moduleangular-cli will add reference to componentsdirectives and pipes automatically in the app.module.ts. If you need to add this references to another custom module, follow these steps:
2.       call ng g component new-module/new-component
This should add the new componentdirective or pipe reference to the new-moduleyou've created.

Updating Angular CLI

If you're using Angular CLI 1.0.0-beta.28 or less, you need to uninstall angular-clipackage. It should be done due to changing of package's name and scope from angular-clito @angular/cli:
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
To update Angular CLI to a new version, you must update both the global package and your project's local package.
Global package:
npm uninstall -g @angular/cli
npm cache verify
# if npm version is < 5 then use `npm cache clean` 
npm install -g @angular/cli@latest
Local project package:
rm -rf node_modules dist 
# use rmdir /S/Q node_modules dist in Windows Command Prompt; 
use rm -r -fo node_modules,dist in Windows PowerShell 
npm install --save-dev @angular/cli@latest
npm install

Some Useful Flag for Angular CLI.

1.     To open project automatically in a browser Tab
ng serve --o
OR
ng serve --open
2. Create project with routing file by default
ng new ProjectName --routing
3. Run project on different Port (Apart from default Port 4200)
ng serve --port 4201
4. Changing Base href while build
ng build --base-href=yourValue
OR
ng build --base-href /myUrl/
5. For performance of your application
* ng build --prod
* ng build --aot
6. Adding custom prefix for new project
ng new your-project --prefix custom
7. For Inline Template/Style of your component
ng g c button --inline-style --inline-template
You can anyone as per your requirements.
8. Avoid Hashing of file names while bundle your application
ng build -prod --output-hashing none
OR
ng build -prod --output-hashing=none

Sunday, February 18, 2018

JavaScript rewrite URL


if (document.URL == "http://www.domainName.com/") {
console.log(document.URL);
        var restOfUrl = window.location.href.substr(11);
        window.location = "http://" + restOfUrl;
    }

Comments are welcome