首页
动态
文章
百科
花园
设置
简体中文
上传成功
您有新的好友动态
举报
转发
养花风水
12月23日
养花风水

Introduction to Javascript Frameworks (React Basics)

In the modern era of web development, the libraries and frameworks assist the software developers in creating complicated and efficient applications. One of the most commonly used and popular frameworks in the past couple of years has been React. It was initially developed by Facebook and it enables developers to create rich, interactive web applications easily. In short, it is a modern way of developing web applications, and we all know how powerful web applications can be for a developer.

Before discussing the reasons for the adoption of React, it makes sense to discuss what JavaScript frameworks are to begin with and then proceed to the underlying principles of React.

Indeed, What is a Javascript Framework?

A JavaScript framework can be defined as a set of ready-made JavaScript code for constructing applications in the fastest manner possible. Frameworks give a blueprint and a set of instruments to a developer, so he or she is able to concentrate on the core idea of the application and its programming, instead of systematizing the standard code. There are several Javascript frameworks that assist in structuring application code, provide front-end UI features, or provide connectivity between the presentation layer and the data centre.

Moreover, it has wide-ranging capabilities which makes learning it worthwhile. Starting from algorithms teaching and all the way to complex game design. JavaScript frameworks are an incredible asset when developing applications across wide disciplines. Understanding such programs as Angular, Vue and React will facilitate the work tremendously. But these applications are, however, usually called libraries rather. If you look closely, these programs are nothing more than powerful user interfaces. Naturally, it enables the development of more robust frameworks and libraries.

Why React?

Out of several JavaScript frameworks, learning React seems to be the best investment. Many people still confuse React with other frameworks and libraries bundled together with its namesake, some call it 'ReactJS', others simply refer to it as the UI framework. To clarify, let's look at some of the features of React that answers the question of why should anyone become an expert React developer.

1. Component-Based Architecture: One of the fundamental aspects of any application written in React is how the application is structured. First off, let's understand what it means to have a Component based architecture. In its simplest form, any given website or web app can be divided into different parts or segments. So, you can think of these segments as pieces. This includes headers, footers, and body sections, images widgets and all other UI elements that went into building said application. So essentially, a single application is made up of several other applications that are embedded within one another. This modular design greatly simplifies management, testing and updating processes as changes to different parts can be made without altering neighboring ones.

2. Declarative Syntax: As already stated, React implements a declarative syntax instead, meaning that developers consist solely on defining what they want in a given user interface, and in this case, React executes how to do it. To put it another way, instead of writing imperative code that details each stage of the operation, React developers only need to specify the front-end design of the interface, and whenever such a state is needed, React will do the house updating when the state changes. This means that applications built with React are also less difficult to read, debug and maintain.

3. Virtual DOM: One more important aspect of React is Virtual DOM (Document Object Model). Virtual DOM is used in optimizing the update of the user interface as it is a replica of the actual DOM, only that it is much smaller. When an application is changed, React will first change it in the Virtual DOM, and only then will check for changes in the actual DOM. Then, only the changes that should be made to the actual DOM are done enabling speed as well as reducing unnecessary re-rendering.

4. Unidirectional Data Flow: According to React, components and data can only go in one direction, data always flows in one direction, components receive details of their parent components through properties, which are often regarded as 'props'. If a component wants to revise its data, it needs to revise its state, which will reactivate the rendering of the component. This iterative and systematic data flow makes it comparatively easy to perceive how the data changes in the app and how those data changes impact the UI of the app.

[图片]5. JSX (JavaScript Syntax Extension): JavaScript has a syntax extension known as JSX, and React works using JSX, this makes it possible to write HTML code directly inside JS, as long as it has a similar structure. It is possible to create user interface elements in a more usable and familiar format together with the power and utility of JavaScript. Tools such as Babel enable the browser to execute code that wasn't meant for that in the first place by converting JSX to Javascript since browsers are not designed to interpret it.

Getting Started With React

To begin working with React, one must acquire certain tools and libraries in a development environment. The best way to get up and running with React is to use Create React App since it is a tool endorsed by Facebook that initializes a React application with all the configurations such as build tools, application structure, and libraries.

Once you create a React application, you will come across a folder structure which would consist of the following main components:

- src: This folder contains all the source code for your application, here you'll define your components and logic.

- public: This folder contains the static files, in particular the index.html file, images or icons.

- node_modules: This folder holds all the required dependencies for your project.

- package.json: This is a crucial file that contains a list of all the dependencies and scripts used in your project.

Most development environments normally employ Webpack and Babel amongst other tools to assist in a myriad of tasks such as combining and transcribing your Javascript files into a version that the browsers can comprehend.

What are the Different Types of Components in React?

As far as I know, React is a JavaScript framework that allows developers to build user interfaces as component hierarchies that can consist of several nested components. Each component can render an interface and can be written as a function or class. Components can be divided into two types: Class components and Function components.

- Class Components: These components represent a class that extends `React.Component`, they are the most complex form of React components. A class component must have a `render` method and return some JSX.

- Function Components: As the name suggests, function components are entirely produced as functions. At the beginning, these classes didn't support state management but thanks to the Hooks in React, they can do every function class can, in addition to being stateless.

In most cases, a component will receive `props` as one of its parameters and will be responsible for rendering corresponding HTML and/or JSX code. `Props` are essential in react components because they facilitate the flow of data between nested components.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水

Web Storage APIs: Local Storage and Session Storage

In web development, Web Storage API has become one of those things that we cannot ignore. They provide a means to store information on the client-side (browser). These APIs help websites remember information such as user preferences and also maintain state across various sessions or pages. Local Storage and Session Storage are probably the most used web storage mechanisms. Both allow end users to save data on the client-side but work differently in terms of its range and lifetime. Grasping these distinctions and understanding under which conditions they are most suitable for use can considerably enhance the efficiency and capability of web apps.

What is Web Storage?

Web Storage is a client-based storage system that lets web applications store key value pairs in a user's browser more conveniently. While cookies contain data that must be sent through the server with each HTTP request , data that has been stored in Web Storage is only available to JavaScripts on the Client side. Therefore, Web Storage has the potential of providing a better and less network intensive solution for storing data.

Web Storage has two primary components as outlined below:

1. Local Storage

2. Session Storage

Although both have similarities, it is important to know the variation between the two to be able to use them appropriately.

Local Storage

Local Storage is among the variety of Web Storage APIs that uses client-side storage to keep data on the web browser. Local Storage is unique in that data stored in it does not have an expiration time set and remains in the browser even when the user closes the browser or the tab. Because of this, Local Storage is best suited to store any information which must be accessed over multiple sessions.

Data held in the Local Storage is classified in key-value pairs and can be invoked through JavaScript programs belonging to the same domain as the data. Each domain (or origin) has its own isolated storage, so data stored for one website can not be accessed by another.

Local Storage Examples

// Store data
localStorage.setItem("username", "john_doe");

// Retrieve data
let username = localStorage.getItem("username");

// Remove data
localStorage.removeItem("username");


Local Storage has a good amount of space (in most cases, 5MB is the limit per origin) so it is best used to store non-sensitive such as user preferences, theme settings, app configurations etc. One point to keep in mind is that Local storage is available to any JavaScript running on that page which is why no sensitive information should go there as it does not get encrypted.

[图片]

Session Storage

Like Local storage, Session Storage is also one of the Types of client storage. However, they do differ in one aspect:.Session Storage only contains data that was used during that page session, so the data contained is for that session only. A page session is active as long as the user has the browser tab opened. Once the tab or the browser is closed the data from the session storage will be deleted.

Session Storage Examples

//store data
sessionStorage.setItem("sessionId", "12345");

//get data
let sessionId = sessionStorage.getItem("sessionId");

//delete data
sessionStorage.removeItem("sessionId");


The beauty of Session Storage is that all the information is wiped out the moment the tab is closed. That's why it's helpful for forms with many steps, or even just browsing the same page.

How Local Storage Differs from Session Storage

Both Local Storage and Session Storage allow key-value pairs to be stored on the client-side. However, there are a few differences that set them apart. Knowing these differences makes it easier to choose the storage type best suited for the needs of your application.

1. Persistence

- Local Storage data does not get deleted simply by closing the browser or browser tab. It sticks around until the user or program explicitly deletes it.

- Session Storage data is removed once the browser tab is closed. It is session-oriented and when deleted, does not persist over different sessions or tabs.

2. Scope

- Local Storage can be accessed from any tab or window with the same origin (which is the domain).

- Session Storage is limited to a single tab of a web browser only. There is a unique Session Storage for every tab so one tab cannot access the Session Storage of the other tab even if both of them are on the same website.

3. Storage Size

- The noteworthy aspect is that both Local Storage and Session Storage allow a maximum of 5MB of data for each origin. Nonetheless, it is important to note that they have the same storage size which makes it irrelevant in this case.

4. Use Cases

- Local Storage : This is appropriate for information which is needed to exist longer than a single session – like user preferences or any tokens for authentication, token and data, application configuration and so on.

- Session Storage : This holds session specific information such as form input, IDs and so on that is only used during one particular session.

5. Data Access Restriction

- Local Storage and Session storage is only available to the single same origin which has the domain, port and protocol same. This avoids websites being able to read information stored by other websites.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水

Using JavaScript for Animations: The HTML5 Canvas and SVG

Animation today is arguably one of the key components for any contemporary website as it enhances the interactive element of the site. Thanks to the introduction of HTML5 together with JavaScript, animators now have animation creation tools that are easier to use and perform. Two of the most common ways of performing animations in JavaScript are the HTML5 Canvas and Scalable Vector Graphics (SVG). On one hand, using both technologies allows users to work with images on a web page, but on the other hand, it enables them to do it in quite an opposite manner. For those who want to be successful in web designing, it is necessary to know how to use these two tools in animation.

Definition of HTML5 Canvas

The HTML5 canvas element is a graphics canvas that is dynamically generated on a webpage via scripting language, such as JavaScript. This means Dynamic images, drawings, and graphics can be created and manipulated within a web page. This would be achieved without the use of content that is embedded in the canvas. The canvas element provides a space for JavaScript to make images but does not itself contain any images.

The canvas method by itself provides quite a broad range of methods for managing the pixels inside the canvas boundary which includes drawing of images of lines, shapes and images, styles, and also transformations. Since the Canvas is pixel based it means it works with pixels individually and renders images on to the screen.

To do this, the canvas has to be declared in HTML and its width and height attributes set. Then it can be accessed through JavaScript, in order to enable it, certain codes have to be driven into the context for the purpose of content modification associated with the inside of the canvas.

Declaring Canvas in HTML



Accessing Canvas in JavaScript

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");


Animating with the Canvas

Drawing new images of frames and putting them in succession one after another makes animation in the canvas appear which in turn displays the frames that have been drawn previously which is enabled through properly timed drawing using the `requestAnimationFrame` method.

Basic Canvas Animation Example

let x = 50;  // Circle's first pixel in the x axis
let y = 50;  // Circle's first pixel in the y axis
function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);  // Let's erase the last circle
    ctx.beginPath();
    ctx.arc(x, y, 20, 0, Math.PI * 2);  // Place a circle in the center
    ctx.fillStyle = "red";
    ctx.fill();
    x += 1;  // Increment x position by 1 Pixel.
    y += 1;  // Increment y position by 1 Pixel.
    requestAnimationFrame(animate);  // Move on to the next frame and repeat.
}
animate();  // Drawing and looping the animation.


As observed in this example, the method `clearRect` clears every frame that comes after it and the circle is to be drawn again at different coordinates in every frame. Adjusting the parameters for the `x` and `y` coordinates while redrawing the circle over and over makes it look like it is animated smoothly.

What is SVG?

SVG or Scalable Vector Graphics is one of the concepts used in creating graphics in web development. It is different from Canvas which uses pixels to create images since SVG is a vector. Hence, images made using svg can appear in any size as images are composed of paths. It is also important to note that SVG graphics are created in an XML format hence the lightweight nature and they are also easily modifiable via text.

Most of the time SVG is used in designing logos and icons and even other graphics since it is resolution independent meaning an image of any size can never appear blurry. Moreover, since CSS and Javascript can be used to style and animate SVG elements, they can also be effectively used in web interactive animations.

[图片]

Animating with SVG

Even though SVG is primarily a static vector format, javascript can be used to animate SVG elements. This renders it easy to animate elements on SVG as opposed to canvases where the entire scene would have to be erased and redrawn.

SVG Animation Example


    



As noted in this example, the SVG rectangle is animated using the `setAttribute` method whereby the `x` and `y` position values of the rectangle are changed, moving it from one to several specific points or corners.

Apart from animating shapes using Javascript, CSS can also be used in animating SVG elements. For instance, one can animate a shape's fill, its opacity or location through the application of `transition` and `animation` effect of the CSS elements. This is however much better when Java is included because one can create unique and intricate animations effortlessly.

Canvas and SVG – What's the Difference?

Both can create animations but canvas and SVG seem different. Canvas is rather meant for creating animations or games where loads of interconnected pixels would be involved. Canvas makes creating pixel-based graphics easy. In contrast, many suggest SVG for any logo, icon or similar situational vector graphics that you can easily scale up or down.

Canvas is more suited when a number of graphics at the scene need to be drawn and the scene has lots of changes. But for animating single objects, it has disadvantages since every scene needs to be drafted again and again with each moving frame. Since SVG graphics are vector based, they will work for animations which are limited in the number of moving objects and will maintain their sharpness in all resolutions.

Both have their pros and cons and the decision to go with either of the two mainly focuses on the graphics detail and the animation that you require.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水
The Fetch API is one of the crucial technologies that allow for the smooth and effortless creation of Web apps. It is a known fact that building user-friendly interfaces is a core aspect of web development in this modern age. One of the techniques that allow for this is by enabling the exchange of data between a web page and a server without the need to refresh the web page. As a result, the experience gets better and the web page feels more interactive. Hence the introduction of this powerful and effective technology, Save us from the crutches of the conventional and outdated XMLHttpRequest. Allowing us to focus on creating efficient and functional applications.

The purpose of this article is to discuss the Fetch API – what it does, how it works and where it can be efficiently utilized in Web development. In web development, one must have come across the term Asynchronous calls, this is because they are the cornerstone of creating a responsive application. Which is why the Fetch API is as important – More specifically the Promise aspect of it.

What is the Fetch API?

Fetch API is a new interface that allows servers to communicate with Javascript through HTTP requests. That way, there's no need to refresh the webpage every time you want to get new data from the server. The Fetch API is basically a better version of the older XMLHTTPRequest API, allowing for more complex and effective ways to initiate requests.

The Fetch API is better than its predecessor XMLHTTPRequest as it does not make use of call back functions instead it relies on the usage of promises. Asynchronous functions can be complex, but promises make it easier to manage them. Future completion that would dictate if the request worked or not - with the value depending on the latter, would be held by the promise.

With the fetch API, however, the application is able to send and receive other types of requests like GET, POST, PUT, DELETE and others. Other modern aspects like the ability to work with JSON responses and passing custom headers, sending credential requests are also supported.

What Is the Purpose of the Fetch API?

The Fetch API serves one purpose which is to send HTTPS requests to a server. This whole cycle starts once JavaScript calls the `fetch` method with `resourcelocator` `fetch('https://example.com/resource')`. End this method results with resolving the promise with Response containing the data obtained from the server.

Fetching API is versatile and supports a wide range of input parameters chiefly including querying a database, actively pushing the information obtained from UI, or even invoking files located on another server. The syntax is straightforward yet offers a great variety of simple and advanced requests functionality.

Basic Fetch Example

fetch('https://api.example.com/data')
.then(response => response.json()) 
.then(data =>{
    console.log(data);
})
.catch(error => {
    console.error('There was an error!', error);
});


In this example, the `fetch` function then takes in a URL and uses the GET HTTP method to fetch resources for that URL. After the requested URL sends its response over to the server, the javascript `then()` method proceeds to execute the code in it. The `response` token passed is an object containing the response received from the targeted server. In order to retrieve the information from this object which is in the form of JSON, `JSON.parse` is done using the `response.json`. Finally, to complete the process, the data is output through logs by `console.log`.

If there is an error (for instance, the server is unreachable), the error is reported because it has been logged using `console.log` in the `catch` method.

Fetch API Response Handling

Always remember that when using Fetch API, knowing how to manage the response of the server is very important. A response object has a number of methods that when used allowfor the processing of the data. Some of them are quite common and can be used in this particular case with the Fetch API.

[图片]1. response.json(): The response returned from the server can be a valid string in JSON format - this method approaches that string and formats it as a javascript object.

2. response.text(): If the server has sent the data in non-JSON format, for instance, returning an HTML or a simple text file, this method retrieves it and responds with it as plain text.

3. response.blob(): Servers might store images, videos, or other files specifically in binary data. This method is relevant here as it serves to retrieve the mentioned binary data.

4. response.status: When questions around whether the request was successfully processed - was there an error or not, arises, this property is relevant as it holds the answer by storing the HTTP codes.

Response Handling Example

fetch('https://api.example.com/data').then(response => {
    const statusCode = response.status;
    if (!(statusCode >= 200 && statusCode < 300)) {
        throw new Error("Network response was not ok");
    }
    return response.json();
}).then(data => {
    console.log(data);
}).catch(error => {
    console.error('There was a problem with the fetch operation:', error);
});


In the above example, therefore it was decided to use the `response.ok` property which returns a boolean value that is true only if the server response was ranging between 200 (successful) to 299. If this is not the case, an error is returned.

Using Fetch for POST Requests

A common applied POST request is to send data to the server, while GET is mostly applied to get a request for the server so to say the two are almost complete opposites. The Fetch API also has an option for you to set the method to POST where you can specify headers and body content.

Fetch POST Example

const data = {
    username: 'john_doe',
    email: '[email protected]'
};
fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
    console.log('User created:', data);
})
.catch(error => {
    console.error('There was an error!', error);
});


Here we create a `data` object which consists of users' data and we use the `fetch()` function with the `POST` method and the `body` option holds the stringified JSON data and with the `headers` option we mention that we're sending data in JSON format.

Fetch API and Catching Errors

One of the important aspects of working with the Fetch API is error handling. A fetch request can fail for many reasons, for example, incorrect URL path, server malfunctioning, or network issues. Fetch API does not throw an error on its own for the failure HTTP status codes (like 404 or 500). Instead, it only throws a rejection of the promise if there is a network problem or the request has been unsuccessfully completed.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水
Modern dynamic and interactive websites correctly rank among the cut-throat expectations of the users. People want websites which respond to their inputs and interactions instantly, load new information without the need of refreshing the whole page and engage the user throughout with persistence. It is at this point that JavaScript and AJAX come into the picture. In unison, they make it possible for developers to come up with dynamic pages which are responsive in nature and most importantly they feel fast. In this review, we detail on how Ajax and JavaScript function with respect to one another to facilitate the building of dynamic web applications and improving the user's experience.

The Key Components of a Complex JavaScript Architecture

Java Script is probably the most important and versatile of all coding languages, for a developer, as he is able to run his code in web browsers. This allows web pages to be manipulated to be JavaScript enabled. Websites are made interactive by replacing contents on the page through a Java script that is able to add or change an HTML document. Moreover, Java Script makes it possible to update an HTML document by creating a web page that responds to associations with external sources. This includes but is not limited to dealing with clicking requests and keyboard tapping orders which are commonplace in webpage creation.

JavaScript is predominantly popular due to its capability to work with other languages and components. In this case, HTML elements can be viewed as nodes in the DOM tree structure. Thanks to JavaScript, the document object model can be altered dynamically to reflect a user's actions and their related results on a website's content, its looks or its arrangement.

For example, through the use of JavaScript, the content of a certain paragraph can be altered, elements can automatically display themselves or disappear depending on whether the user clicks them or not, and even a form can be submitted without the need of reloading the page. Such possibilities can greatly enhance the interactivity of a website and the responsiveness of its features as there will be no need to reload the entire page after every single action.

What are the Risks of Not Using AJAX While Web Designing

But there is one more concern which JavaScript does not solve: how do I fetch and change server data without refreshing the entire page? The inherent approach to every web development task is the idea that whenever a user wants new information, the browser contacts the GET server through a new request and the new information is loaded within the entire window along with everything else. Such routing can be inconvenient to users, especially in large pages.

This is now where AJAX fits into the picture. AJAX is short for Asynchronous JavaScript and XML. In a more in-depth description, AJAX is a technology that lets web pages exchange information with the web server even without refreshing the page. Thanks to AJAX, web pages can now update smoothly. After a webpage is loaded, and whatever data is required is requested from the server, Javascript can request data, process the data, and update the web page, all at once. As such, this means web pages will become faster and more effective when it comes to user interaction, all thanks to AJAX.

What Happens Behind AJAX?

With AJAX, parallel processing of information is made possible in a web page that is quite loaded with a lot of scripts running. For instance, a single page interacting with a multi level server network also relying on a SQL server whose response would take some time. So a typical AJAX request works like this when a AJAX enabled page is fully rendered and being requested, the request gets sent and the JSX code of the AJAX request gets executed and also the native Javascript code present on the page keeps running, retaining the responsiveness of the web page. When the desired data is achieved, the rest of the page goes about rendering as per requirement.

The key ingredient of AJAX frameworks is utilisation of web browsers. AJAX relies heavily on the helper technology of XML, Facebook API/REST plugins. When building an interface, Javascript communicates to a server operating with Virgin Inspector organisms implementation whether through XML or in other instances with JSON. Instead, a newer and more resilient web interface aims to stimulate interaction.

AJAX, Asynchronous JavaScript and XML is basically used to request or download the data to and from the server. It is widely used as it makes it possible to make a web application faster and more interactive.

In an AJAX call/ request there's always a standard function which will help you understand how data gets transferred and submitted to and to other web applications. Here are the steps:

[图片]1. Sending request: This is when JavaScript wraps up a request for information and sends it to an external server. The data that can be retrieved can be in the format of text, Json or even XML.

2. Making a request: Then after wrapping up a request, a request is made to the server through a client's browser. This will not refresh the current web page which allows users to work on it while a request has been sent.

3. Processing Dominating: This tells us how the request was made, what was the outcome for the request and if the request needed to retrieve or store any data.

4. Response Receiving: In this phase we determine the server's outcome. The server sends the information back to the client's browser in a language which JavaScript would understand like JSON.

5. Browser page Revision: This will allow a user to revise a web page without refreshing it.

JavaScript with AJAX

JavaScript stands out to be a very important language when it comes to AJAX. It covers all the three phases of making a request till the data is updated on the page. The most basic use of the language is to not make changes to an entire web application but to change only parts of it. This can be done through the document object model modification and updating after the request has been fulfilled by the server.

The above is true as you can see, JavaScript assists with the handling of any problems such as server downtime for an AJAX request which can potentially crash the application, as JavaScript handles the said problems by conveying the issues to the user.

AJAX and JavaScript Integration – Why Use This Combination?

During the combination of JavaScript and AJAX, a lot can be done in relation to the development of pages for a website. One of the greatest advantages of these technologies is their combination allows for creating fast, user-friendly web pages that don't have to be fully reloaded. Here's why JavaScript and AJAX for dynamic web pages are an important set of technologies:

1. Enhanced User Experience: Due to AJAX being employed for dynamic content loading, it means that a user does not have to entirely wait for the page to change. Rather, content is refreshed even as a user is scrolling through new elements on a page, meaning that users experience less waiting time and an overall quiet seamless experience.

2. Saves Server Resources: Rather than sending requests to the server about the whole page to be pushed out, AJAX enables a system to only request the necessary data to be used. This in result minimizes unnecessary requests from being sent to the server which in turn is more efficient.

3. Web Pages with Significantly Higher Speeds: Because AJAX only updates the required data, web pages have lower load times which are essential for users' experience. This is especially crucial for single-page applications requiring dynamic data without a complete system refresh.

4. Increased Engagement with Users: Thanks to AJAX integration, JavaScript enables the developers to build engaging features such as live search, infinite scrolling, and live chat that boost the user experience.

5. Flawless Changes within a Page: Thanks to AJAX, updating the content no longer demands reloading the page, making it convenient to send out notifications or updated information real-time communication without any disruption on the user's activities.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水
JavaScript has to be one of the most common programming languages we use while building websites. Now, as the applications get more sophisticated or intricate, the need to break down the code into simpler and smaller, reusable and maintainable chunks becomes more and more apparent. This is where JavaScript modules come in. They assist developers in maintaining clean coding practices by splitting them into more comprehensible and more manageable sections. In this post, we will discuss what JavaScript modules are, how they are relevant, and how they change the structure while enhancing the functionality of the JavaScript code.

JavaScript Modules- Concept and Scope

In case you haven't had any idea, a JavaScript module enables developers to divide their codebases into smaller or lets say modular encapsulated components. Each module may include variables, functions, classes that correlate respectively in terms of completing a task or serving a specific feature. This separation makes it possible to create, run tests, and maintain high-level, advanced applications. Earlier, developers had to struggle since JavaScript did not support modules. So all the functions and variables were globally stored which became a hassle to manage which eventually had a lot of errors.

To solve these problems, the module system was one of the features added to JavaScript. Now, thanks to modules, developers can bundle the code in different files and import and export sections of code where they are necessary. This modular development enhances code but also prevents complications that arise from variables being global.

What are JavaScript Modules and How Do They Work?

JavaScript modules export and import code from one another. This is one of the solutions that these modules provide.

1. Exporting

There are two types of exports: named exports and default exports.

First, code from one of the modules must be exported in order for it to be used by other modules.

- Named Exports: These are helpful in exporting more than one object or a function from the module. In order to export, the `export` keyword is written before the particular function or the variable that you want to export.

[图片]

Named Exports Example

// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;


- Default Exports: This enables a module to implement sole default export whether it's a function class, or an object the module is restricted to a single default export.

Default Exports Example

//Dummy.js
const logger = (message) => {
    console.log(message);
}
export default logger;


2. Importing

When a code is exported from an inter module, it can then be imported using the `import` syntax to other intermodules within the project connected via the statement.

- Importing Named Exports: While recalling a named export, the bracket curly must be in the same syntax as the named export.

Importing Named Exports Example

//Dummy2.js
import {add, subtract} from './math.js';
console.log(add(2,3)); //5
console.log(subtract(5,3)); //2


- Importing Default Exports: Importing the said module does not require the use of the export mention since there is and can only be one default export which is common in every module.

Importing Default Exports Example

//app.js
import logMessage from './logger.js';
logMessage('This is a log message!');


Benefits of Using JavaScript Modules

There are quite a number of benefits of using modules in JavaScript as listed below:

1. Better Code Structure

It might be a bit hard to handle all the codes that are written in one file as projects get larger and more complex. That's why the use of modules is important, because they allow you to separate codes logically and by their purpose and this makes the logical structure much easier to comprehend. For instance, all logic regarding user authentication could reside within a module and all logic concerning interactions with the database could reside within another module. In that case, developers could develop only one aspect of the application at a time.

2. Avoiding Code Duplication

After creating each utility function, it gets easy to reuse or call it in any part of your application. For example, suppose a module is created that formats dates, and this module is subsequently imported into various others. In this case, all would be well because calling multiple copies of a module adds nothing and increases complexity without adding benefit. This decreases replications and increases manageability since changing the utility function would only have to be done in one spot.

3. Minimizing Global Namespace Pollution

The major problem with traditional JavaScript is its use of global variables and functions, as this allows multiple parts of the program to use the same variable or function which causes conflicts and bugs. On the contrary, modules provide a way in which the variables and functions defined by you are defined into the range of the module and this minimizes the risk of conflicts whilst maintaining the neatness of the easier Javascript namespace.

4. Simplified Testing And Debugging

As a result of modules containing or encapsulating a certain set of features, it becomes easy to test and identify problems in pieces of code without interfering with other parts of the application. For instance, with the help of an in-built debugger such as Chrome DevTools, if a bug develops in a single feature of a program, the only part that will be affected is the module that facilitates that feature, and thus the debugging is done in a targeted manner without affecting the whole program.

5. The Use Of Dynamic Imports

The good thing about JavaScript modules is that you can use the dynamic type of imports alongside it, which allows you to import modules dynamic imports equates to the ability to only pull modules when they are actually needed; this comes in handy when you want to reduce the application's initial loading duration when needed. Frameworks that allow for lazy loading/large applications will particularly benefit from the use of dynamic imports.

Dynamic Imports Example

button.addEventListener('click', () => {
    import('./notThatSmallModule.js').then(module => {
        module.testButton();
    });
});


This pattern of code will allow you to break down your code into various small blocks that will load whenever they are needed instead of loading all at once.

ES6 Modules and the `` tag. By doing this, you assist the browser in decoding the script as a module allowing for the `import` and `export` elements to be used.

Using Modules in HTML



This tells the browser that `app.js` is a module and that it should be handled and implemented in that manner as well. This also makes sure that the module is always loaded with its own scope so that there is no risk of overwriting the global namespace.

...显示更多

0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水

Creating Interactive Forms Using JavaScript

Forms play an integral role in web development. They allow users to provide data, make transactions with the sites, and carry out other functions, for example, signing up or in, giving feedback and so on. Creating forms has been made a piece of cake by HTML, however, the most interesting bits in creating forms are made possible by the use of Javascript. This means that forms created using Javascript can have moving parts, for example, elements inside the form can be changed, validated, or updated depending on the user's interactions. In this article, we will dive deeper into the world of Javascript and see how it can be applied to make forms more engaging.

Deciphering the Anatomy of a Form

As far as HTML is concerned, a typical form has a number of input elements such as text boxes, radio buttons, check boxes, a drop box and a submit button. Such elements are all enclosed within a tag called `
`. The primary objective of a form is to gather user details, which is why the `` tag also has the `action` and `method` attributes that help to identify where and how the details provided in the form will be forwarded once the form is submitted. But for a form to be engaging then Javascript has to be implemented.

We'll work with the HTML form:

Basic HTML Form

<form id="contactForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <button type="submit">Submit</button>
</form>


The HTML code above demonstrates a basic form with input fields for a name, email, and a submit button. The way the functionality is designed very simply, when the data is filled, the page gets refreshed and the information filled in the form is sent over. But thanks to JavaScript we have a chance to reshape it.

Enhancing Usability Through Javascript

It provides a structural base however forms are made interactive using JavaScript. Within the JavaScript, tasks can be set in order such as form input requirement checking, auto filling forms, and content replacement or adding without reloading the page.

1. Filling out the Form

Filling the form allows the users to put in relevant information and is completed after the requirements are checked. Before you send the filled in form to the server. Some of the things to look out for are making sure all required fields have some values filled in and/or the email address is in a valid format. And this is where the use of JavaScript comes along.

Form Validation Example

document.getElementById("contactForm").addEventListener("submit", function(event) {
    let name = document.getElementById("name").value;
    let email = document.getElementById("email").value;
    if (name === "" || email === "") {
        event.preventDefault();
        alert("All fields must be filled out.");
    }
});


In the above examples , the `submit` event listener checks the name and email before sending the form, so these fields are not empty. If there is any blank space on the name and email field , the `event.preventDefault()` method will cancel the submission of the form using an alert.

[图片]

2. Input feedback on real-time basis

Apart from checking the validation of the form after the submission, form submission can also be a feature which allows to give feedback on real time to the users while they are filling the form, for instance highlighting correctly filled fields or where the user has filled in data incorrectly, or even providing feedback on whether the user's email address is correct or not.

Real-Time Email Validation Example

document.getElementById("email").addEventListener("input", function() {
    let email = this.value;
    let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6}$/;
    if (emailPattern.test(email)) {
        this.style.borderColor = "green"; // Valid email
    } else {
        this.style.borderColor = "red"; // Invalid email
    }
});


This script takes into consideration the validity of the email format when a user changes the email input. In case the email structure is corrected the border of the email input will be colored green, in the opposite case the border will be red. This will not only help users comply with the format but also visualize what is needed.

3. Adaptive Form Fields

Java,Script must be the code,among other the code which enables form fields to be usably altered through inserting key elements. For instance, if a customer wishes other fields to appear on the form, they can, in turn, add/subtract fields.

Adaptive Form Fields Example

document.getElementById("newsletter").addEventListener("change", function() {
    let newsletterField = document.getElementById("newsletterType");
    if(this.value =="yes") {
        newsletterField.style.display = "block"; // Show newsletter type field
    } else {
        newsletterField.style.display = "none"; // Hide it if "No" is selected
    }
});


In this scenario, the consumers specify whether they wish to receive the newsletter, in which case a new field requesting them to specify the type of newsletter they would like to receive appears. It is the capability of JavaScript that makes this kind of dynamic change without refreshing the page.

4. Submission of Form

After all the required fields in the form have been filled and the form data validated then you can proceed to getting the form submitted. In the conventional way, sending a form would imply sending the data to the server and the page being reloaded; with the help of JavaScript this is not necessary, it is now possible to send the form data even without reloading the page enabling better user experience.

AJAX Form Submission Example

document.getElementById("contactForm").addEventListener("submit", function (event) {
    event.preventDefault();
    const formData = new FormData(this);
    fetch("/submit-form", {
        method: "POST",
        body: formData
    })
    .then((response) => response.json())
    .then((data) => {
        alert("Submit form successfully!");
    })
    .catch((error) => {
        alert("An error occurred in course of submission.");
    });
});


In this case after a form was submitted, its data was sent to the server using the `fetch` method without refreshing the browser. As a result the user gets a success or error message depending on what the server sends back.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水
A number of new features made their ways into javascript with the introduction of its gallant version ECMAScript 6 or ES6. These features worked towards the goal of creating a language that's powerful, abstract and easy with great effectiveness. It is recommended for anyone who is seeking to bridge their knowledge in javascript or is starting out to know these main points of ES6. This article's focus will be shifted to some of these features along with their effect on the cutting edge javascript development.

Let and Const

As of writing this article, 'var' was the only keyword previously available to create variables in JavaScript. Although the `var` keyword was useful for declaring variables, it also came with negative aspects concerning scope and hoisting which can create bugs and make codes more messy than they need to be. Two new ways of declaring variables were introduced with the enactment of ES6. These were `let` and `const`.

1. Let: Block scoped variable can be accessed only inside the block in which they were declared, be it a loop or an if statement, and it can be done through the use of the keyword `let`. This overcomes the potential complications offered by `var`, as the scope of the variable is more easily understood.

2. Const: It is worth noting that Const is a nominative program that allows to declare constants which means that these variables are never changed, they are initialized once and for all. This turns out to be less cumbersome while dealing with read-only variables thus increasing the readability of the code by preventing reassignment of a variable by mistake.

Arrow Functions

One of the major features of ES6 which is so popular and in fact everywhere is the arrow function. An arrow function is a special type of function that can enable you to access global variables and have a different context 'this'. This makes them very effective when working with functions or callbacks in objects.

Arrow functions use the syntax '=>'. For example:

Arrow Function Example

let add = (a, b) => a + b;


In this illustration we can say that the arrow function added the benefit of only more parsers seeing that it effectively behaves like a standard function. Perhaps the most noteworthy of all is how arrow functions are able to bind the value of `this` scope passed as an argument during its parent invocation which is quite required in event handling or callback situations.

Template Literals

The other most valuable feature introduced with ES6 is SaaSits easy for a user to use template literals. Instead of quotation template literals allows you to use placeholders along with backticks.

For example:

Template Literals Example

let name = "Alice";
let greeting = `Hello, ${name}!`;


What made the context even more interesting was the quote say hello to Alice. Instead of saying hello to Alice, string concatenation is long gone. Because multi-line strings are supported, longer texts that span several paragraphs are made easier to work with.

[图片]

Destructuring

Another interesting topic that was added to ES6 is Destructuring. When faced with the problem of more optimal ways to unpack values from objects or arrays and write them in variables, ES6 provided a solution to the pain. Rather than reaching for the extreme method of indexing or dot notation, Use of compact form makes the code easier to understand.

For arrays:

Array Destructuring Example

let numbers = [1, 2, 3];
let [a, b, c] = numbers;


For objects:

Object Destructuring Example

let person = { name: "John", age: 30 };
let { name, age } = person;


Writing these statements at the top, the journalist tackles the features of many programming languages, especially those with object-oriented characteristics; the feature is referred to as Pointers.

Classes

Es6 classes only serve to simplify the understanding of smearing for many of us. Objects can be summed up with blueprints methods and inheritance, which of course an architect would like to hope such a simple concept can hardly bring new artistic styles.

A basic class can be defined like this:

Class Example

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    greet() {
        console.log(`Hello, my name is ${this.name}`);
    }
}
let person = new Person("Alice", 25);
person.greet(); // Outputs: Hello, my name is Alice


So far, the built-in JavaScript class examples seem to be an improvement in clarity and structure over the previous prototype-based inheritance model.

Zero Parameters

Previously in ES6, it was possible to use default values for function parameters, as using default values required a function to be invoked with a set value.

Default Parameters Example

function greet(name = "Guest") {
    console.log(`Hello, ${name}!`);
}


As seen in the example, nothing is passed to the `greet` function, so `name` will take on the default value of `"Guest"` in this case. This means we need not have any manual checks or conditional statements inside it.

Rest and Spread Operators

In programming, the sole purpose of flaws is to persuade the two most powerful operators 'rest operator' (i.e '…') and 'spread operator' (i.e. '…') which merge all flaws into the curtains.

1. Rest Operator: The rest parameter makes it possible to pack multiple values into a single array and uses the arrays of the function parameters.

Rest Operator Example

function sum(...numbers) {
    return numbers.reduce((acc,num) => acc + num),0);
}


Here, `numbers` that are parameters of the `sum` function are packed into one array.

2. Spread Operator: The spread operator, the reverse of the rest operator, packs certain properties of arrays or objects into a new entity of its own. It is useful while invoking methods or while declaring new arrays or objects.

Spread Operator Example

let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];


So here, all the values inside 'arr' along with newly added '4' and '5' have been incorporated into `newArr`.

Modules

JavaScript had no concept of modules prior to ES6. The major advantage of modules is in the organization and maintainability of a large code base as you can partition and decompose your code into smaller and more manageable files.

Example of how to export a function or variable declared in a module is as follows:

Exporting Module Example

// math.js 
export function add(a, b) {
    return a + b;
}


And to import the exported function into another file, it is done as follows:

Importing Module Example

// app.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5


In computer programming, especially in JavaScript, modules are very handy as they provide an organized way of writing code and limit the complications that arise due to global variables and namespace pollution.

Promise

Promises are a new feature that was added in ECMAScript 6 to work with functions with asynchronous execution. A promise is an implicit declaration that a certain value may not be available at this point in time but sometime in the future it would be resolved and there would be a value. Whenever an asynchronous operation is to be performed, using promises is much easier due to the fact that they can be chained together with the use of the `.then()` and `.catch()` methods.

Promise Example

let myPromise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Task completed successfully");
    } else {
        reject("Task failed");
    }
});

myPromise.then(result => {
    console.log(result);
}).catch(error => {
    console.log(error);
});


...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水
The aspect of how data can be managed in a web application is among the key features any web developer has to master. One of the most widely adopted formats that is used is JSON (Javascript Object Notation). JSON has a lightweight structure, it is human friendly, and it can be easily converted into javascript objects. The format is practically a standard when it comes to exchanging information between a client and a web server. Thus, to manage data connections, when developing an application, be it an API or a data's inner storage, working with JSON is fundamental.

This article covers the basic concepts related to JSON, its relationship with JavaScript, and the use of JSON within an application.

What is JSON?

JSON is short for Javascript Object Notation. This is a textual format used to represent structured data using the notion of objects which are composed of a set of key-value pairs. Although it is a language neutral format, it is mostly used with Javascript because it is quite straightforward to serialize javascript objects into JSON format and the other way around.

An ordinary object in JSON is constructed using multiple pairs of keys and values. In every single case, the keys are in strings while values may include: String , Number , Arrays , Booleans or even other objects. All of these key statutes are enclosed in a pair of curly braces "{ }" and each statute is separated from the other regulation by a comma. As an example here is a basic format for a JSON object:

Basic JSON Object Example

{"name": " "John","age":"30","isStudent" - false}

In this example:

- For example, "name" can be identified as the Key while "Jewelo's Shining" is the value for that key.

- "age" has the value of 30 and can also be defined as a key.

- While isStudent has a value of false

JSON Syntax Rules

A few essential elements must be maintained while creating a JSON code to operate it effectively and accurately:

1. The object is always kept inside braces `{ }`.

2. Array is used to keep in Partnerhesis `[ ]` along with items that have multiple values.

3. Every Key is required to be a string enclosed inside double quotations i.e. `""`.

4. For every value: it can be either a boolean value, an array of strings, an object, a number or a null value.

5. Every Key- value pair has a relationship which is defined with a semi colon i.e. carved out with` : `.

You can find a more complicated JSON representation that contains arrays and objects:

Complex JSON Example

{ "name": "Alice","age": 25,"hobbies": ["reading", "hiking", "coding"],"address": {"street": "123 Maple St.","city": "Wonderland"}}

In this example, `hobbies` is an array and the other key called `address` is an object.

JSON to JS objects

When dealing with JSON in JavaScript, one of the major requirements is to transform JSON data into something that will be a JavaScript object and can be easily used. This is achieved using the `JSON.parse()` method which is provided by the language.

The `JSON.parse()` method uses one parameter which is a JSON string and returns a suitable JavaScript object. We demonstrate the conversion of a JSON string to a JavaScript object in the snippet below:

Parsing JSON to JavaScript Object

let jsonString = '{"name": "Alice", "age": 25}';
let obj = JSON.parse(jsonString);
console.log(obj.name);  // Output: Alice
console.log(obj.age);   // Output: 25

In the example above, the variable `jsonString` contains a string in a JSON format and enclosed in double quotes. The `JSON.parse()` approaches this string as a JavaScript object allowing `name` and `age` to be properties of an object.

[图片]

How To Convert Javascript Objects Into Json Format

There are instances when a server needs to receive data from a JavaScript code, or say a file needs to be stored, either ways, the content must be converted to a JSON format. Certainly, this can be done by making use of `JSON.stringify()` function, that is converting a JavaScript object to a JSON object's string.

With the following code, we will be able to apply the `JSON.stringify()` method.

Stringifying JavaScript Object to JSON

let person = {name: "Bob",age: 30,isStudent: false};
let jsonString = JSON.stringify(person);
console.log(jsonString);  // Display: '{"name":"Bob","age":30,"isStudent":false}'

This way, the method `JSON.stringify` transforms a JavaScript `person` variable which is a javascript object into a string in json format that can be sent to a server or saved within a file.

Retrieving And Sending JSON Objects Through Web Apps

In web development it won't be a surprise to say that APIs, that is Application Programming Interfaces, are all over and they tend to receive and transmit data in a JSON format. Although, it does seem rather common such as making an asynchronous request to a server.
One common way of retrieving JSON data is by using the `fetch()` function, which is an asynchronous request and returns a promise. Here is an instance of fetching a JSON data and utilizing it:

Fetching JSON Data Example

fetch("https://api.example.com/data")
.then(response => response.json())  // A method that converts the response body// as JSON, which is a response format to // note as well
.then(data => {
    console.log(data); // Add user defined logic
})
.catch(function (error){
    console.log("Error: " + error);
});

In this example, notice the following:

- An HTTP request is executed through the use of the `fetch()` function which passes the designated URL.

- In the `response`, JSON data is parsed and retrieved through the use of the `response.json()` method.

- A Javascript object is also retrieved in the form of a resultant object assigned to the variable 'data'.

- This object can now be used for further manipulating, editing, or displaying.

Manipulating JSON in Javascript on the Server-Side

In fact, javascript isn't limited to the client-side only. Node.js is one alternative where JavaScript handles the server-side client requests. Just like client-side java script, when using JavaScript server-side APIs or working with databases, JSON is also crucial. You may create, read or write JSON files in Node.js utilizing the built-in `fs` (file system) module.

Let's learn how to read and write JSON data with the `fs` module in Node.js with help of the following example:

Reading and Writing JSON in Node.js

const fs = require('fs');
// Reading JSON from a file
fs.readFile('data.json', 'utf8', (err, data) => {
    if (err) {
        console.log(err);
        return;
    }
    let jsonData = JSON.parse(data);  // Converts JSON string into JavaScript object    
    console.log(jsonData);
});
// Writing JSON to a file
let newPerson = { name: "Charlie", age: 28 };
fs.writeFile('newData.json', JSON.stringify(newPerson), 'utf8', (err) => {
    if (err) {
        console.log(err);
    } else {
        console.log("Data has been written to the file.");
    }
});

In this case:

- The `fs.readFile()` function takes the JSON data from a file and `JSON.parse()` function converts the JSON string data into JavaScript objects.

- `fs.writeFile()` function saves a file in which the JavaScript object is transformed into a JSON string using `JSON.stringify()`.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
举报
转发
养花风水
12月23日
养花风水
One of the most difficult concepts that you will encounter in programming is dealing with asynchronous operations. Asynchronous code management in Javascript is important since it helps the applications in such tasks like pulling data from the server, reading files, performing operations which require time. Javascript language facilitates this with the help of promises and use of the async await syntax.

We will provide an overview of these two terms,ones that you will often hear in JavaScript, promises and async/await and discuss their contribution to a better way of writing JavaScript.

What are Promises?

In the programming universe, it is often said that Javascript is the only true asynchronous programming language, this is due to the fact that Javascript contains a myriad of functionality and components that allow for deeper use tailoring such as TIMEOUTS. A promise is one of those components or components that allow an asynchronous request to be made from one component to another, javascript is built around the concept of promises whether you realize it or not it's blended within out the language the same way as Proxies are.

Javascript promises could be said as a Javascript object which aids in the commanding and controlling of other objects, whether they encourage progress or result in failure, depending on how you see them. The concepts behind Javascript promises are China based, using them is simple, generally two command code loops are constructed to issue commands, based on the objects attributes and the output one loop becomes primary enabling the two to speak and the message being sent rounds. This feature is monumental for building and enhancing further functionality down the line enabling far smoother dealing.

When working with asynchronous requests, for instance this could range from network requests to simple database calls, you wouldn't expect it to be instantaneous, hence functional codes are constructed to enable other operations to be carried out while the primary requests are outstanding, bands around the primary request will block secondary loops once that primary request output is recognized , allowing for clean and efficient coding without the use of excessive nested loops.

In computing, the outcome of a promise falls in one of the three categories:

1. Pending: A promise that is issued for the first time will be in the "pending" stage. An operation is still underway.

2. Fulfilled: A promise that has been successfully resolved. A result has been achieved and the operation is completed.

3. Rejected: A promise that has not reached its success is marked as rejected. It can also mean an error or failure was the cause.

The following syntax is used to create a promise: `new Promise()`. This syntax has a function called the executor, which encases the asynchronous task. The two parameters accepted by the executor function are `resolve` and `reject`. When `resolve` is invoked, the task was concluded successfully. However, if it fails, then the `reject` function initiates, indicating that the task has failed.

Here is the basic structure of a promise,

Promise Structure

let promise = new Promise(function(resolve, reject){
// Asynchronous operation
let success = false;
// A piece of code that determines if a success or failure simulation will be fired
if(success) {
    resolve("Operation was successful");  // The promise is fulfilled
} else {
    reject("Operation failed");  // The promise is rejected
}
});

promise
.then(function(result) {
    console.log(result); // If resolved, show the success message.
}).catch(function(error) {
    console.log(error); // If rejected, show the error message.
});
After completing the creation of the promise, you may, however, use the ".then ()" method to add functions to the piecing that you will carry out in the event in case the promise is satisfied. Utilizing the ".catch ()" function aids in solving complications that arise whenever the promise is unsatisfied.

[图片]

How To Chain Promises

As observed, chaining multiple promises one after the other is made possible by the powerful Promises. Multiple asynchronous operations can be chained using `.then`. The successive asynchronous operations are invoked in the order in which they are supposed to be executed.

Here's an example of how chaining works:

Promise Chaining Example

fetchDataFromAPI().then(function(response) {
    return processData(response); // Returning new promise
})
.then(function(processedData) {
    return saveData(processedData); // Returning another promise
})
.catch(function(error) {
    console.log("Error: " + error);
});
In the above example, clearly we can see every other `then` block starts off with a new promise and whichever `then` block comes later can only be executed if the promise preceding it is completed. .Finally, Penny's shoes can only be ordered if – any of the promises in the chain are undone and fail the test, chain-fail bubble-matches shoes undying phones the success of an otherwise percent.

What is Async/Await?

As far as hybridizing the ways of handling asynchronous tasks is concerned, `async` and `await` in JavaScript go a step further, as they extend Pseudo Code, using pseudo logic and utilizing multiple tasks in order to expand for better overall performance of code.

- Function 'async': An 'async' function can be defined as that function which always results in a promise being returned. The definition of the 'async' keyword is also found before the function containing the definition, meaning that a function has the capacity to perform asynchronous operations directly.

- Await: 'Async' functions contain the 'await' keyword which is used to suspend the function's execution until the task is complete.

As a result of using 'await', one mustn't have to perform all the finicky handling of an unwrapped promise thanks to all the unhandled rejection mess. The biggest drawback of using Promises is their over complication. Instead of having multiple nested callback functions, which may be avoided when there is a promise, the use of 'try...catch' is essential every time a promise is created.

Below is a clear example illustrating the combined usage of `async` and `await` keywords at the same time:

Async/Await Example

async function fetchData() {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
    return data;
}

fetchData().then(function(result){
    console.log(result);
}).catch(function(error){
    console.log("Error: " + error);
});
In this example, the `await` keyword defers the execution of the `fetchData()` function until the promised `fetch` call is completed and only then resumes the next line which is a `response.json()` call. Overall, controlling logic flow for asynchronous code is made a lot easier when using async/await compared to plain promises.

Async/Await for Error Handling

Another day you sit down to write code in JavaScript and you know you have to deal with errors. Errors are part of the reliable code and are crucial aspects that need management. Errors when using promises can be handled by the `.catch()` method. Answering the question `how async/await works`, promise errors using the `async/await` syntax you have to use `try...catch` blocks and it will be handled like normal synchronous code.

...显示更多
0
0
0
文章
评论
😀 😁 😂 😄 😆 😉 😊 😋 😎 😍 😘 🙂 😐 😏 😣 😯 😪 😫 😌 😜 😒 😔 😖 😤 😭 😱 😳 😵 😠
* 仅支持 .JPG .JPEG .PNG .GIF
* 图片尺寸不得小于300*300px
滚动加载更多...
article
举报 反馈

您有什么意见或建议,欢迎给我们留言。

请输入内容
设置
VIP
退出登录
分享

分享好文,绿手指(GFinger)养花助手见证你的成长。

请前往电脑端操作

请前往电脑端操作

转发
插入话题
SOS
办公室里的小可爱
樱花开
多肉
生活多美好
提醒好友
发布
/
提交成功 提交失败 最大图片质量 成功 警告 啊哦! 出了点小问题 转发成功 举报 转发 显示更多 _zh 文章 求助 动态 刚刚 回复 邀你一起尬聊! 表情 添加图片 评论 仅支持 .JPG .JPEG .PNG .GIF 图片尺寸不得小于300*300px 最少上传一张图片 请输入内容