Computer Science

Javascript Asynchronous Programming

Javascript Asynchronous Programming is a programming paradigm that allows multiple tasks to be executed concurrently without blocking the main thread. It enables the creation of responsive and efficient web applications by executing time-consuming tasks in the background and handling their results when they are ready. Asynchronous programming is achieved through the use of callbacks, promises, and async/await functions.

Written by Perlego with AI-assistance

8 Key excerpts on "Javascript Asynchronous Programming"

  • Advanced JavaScript
    eBook - ePub

    Advanced JavaScript

    Speed up web development with the powerful features and benefits of JavaScript

    Chapter 2

    Asynchronous JavaScript

    Learning Objectives

    By the end of this chapter, you will be able to:
    • Define asynchronous programming
    • Characterize the JavaScript event loop
    • Utilize callbacks and promises to write asynchronous code
    • Simplify asynchronous code with async/await syntax
    In this chapter, we shall learn Asynchronous JavaScript and its uses.

    Introduction

    In the previous chapter, we covered many of the new and powerful features released in ES6. We discussed the evolution of JavaScript and highlighted the key additions in ES6. We discussed scope rules, variable declaration, arrow functions, template literals, enhanced object properties, destructuring assignment, classes and modules, transpiling, and iterators and generators.
    In this chapter, we will learn what an asynchronous programming language is and how to write and understand asynchronous code. In the first topic, we will define asynchronous programming and show how JavaScript is an asynchronous, event driven programming language. Then, we will outline callbacks and show how to use callbacks to write asynchronous JavaScript. We will then define promises and demonstrate how to use promises to write asynchronous JavaScript. In the final topic, we will present the async/await syntax and simplify our asynchronous code using promises and this syntax.

    Asynchronous Programming

    JavaScript is a single threaded, event driven, asynchronous programming language. What does this mean? This means that JavaScript runs on a single thread and delays/handles certain events or function calls through an event queue. We will break down the basics of how JavaScript does this through the following topic.

    Sync Versus Async

    What does it mean for code to be synchronous or asynchronous? These two buzzwords get thrown around a lot in JavaScript. Synchronous is derived from the Greek root syn , meaning "with", and chronos , which means "time". Synchronous literally means "with time", or rather, code that is coordinated with time. Lines of code are run one at a time and are not started until the previous line has been handled. Asynchronous , or async , is derived from the Greek root async
  • Learn ECMAScript
    eBook - ePub
    • Narayan Prusty, MEHUL MOHAN(Authors)
    • 2018(Publication Date)
    • Packt Publishing
      (Publisher)

    Asynchronous Programming

    Out of all chapters in this book, this is my favorite, because I've faced the consequences of bad asynchronous programming in the past, with callbacks on event listeners, HTTP requests, and basically everything that requires latency. 
    JavaScript has evolved from all these cluttered, unreadable, unmaintainable programming practices and that's what we're going to learn in this chapter.
    Anyway, let's learn what an asynchronous program is. You can think of an asynchronous program as a program consisting of two lines of code, say L1 and L2. Now, we all know that in a given file, the code always executes from top to bottom. Also, it is intuitive such that the code will wait for each line to complete before executing the next line.
    In the case of asynchronous programming, the code will execute L1, but it will not block L2 till L1 is completed. You can think of it as a kind of non-blocking programming.
    In this chapter, we'll cover:
    • The JavaScript execution model
    • Event loops
    • The difficulties faced while writing asynchronous code
    • What are promises?
    • Creating and working with promises
    • How async/await differs from promises
    • Advanced asynchronous programming with async/await
    Let's start!
    Passage contains an image

    JavaScript execution model

    JavaScript code is executed in a single thread, that is, two pieces of a script cannot run at the same time. Each website opened in the browser gets a single thread for downloading, parsing, and executing the website, called the main thread.
    The main thread also maintains a queue, which has asynchronous tasks queued to be executed one by one. These queued tasks can be event handlers, callbacks, or any other kind of task. New tasks are added to the queue as AJAX requests/responses happen, events occur, timers are registered, and more. One long-running queue task can stop the execution of all other queue tasks and the main script. The main thread executes the tasks in this queue whenever possible.
  • Mastering TypeScript
    eBook - ePub

    Mastering TypeScript

    Build enterprise-ready, modular web applications using TypeScript 4 and modern frameworks, 4th Edition

    5

    Asynchronous Language Features

    The JavaScript runtime, whether it is running in the browser, or whether it is running on a server through Node, is single threaded. This means that one, and only one, piece of code will be running at a particular time. This code runs in what is known as the main thread. JavaScript has also been built around an asynchronous approach, meaning that the main thread will not pause when requested to load a resource of some sort. It will, instead, place this request onto an internal queue, which will eventually be processed at a later point in time. While the single-threadedness of JavaScript may take a while to get your head around, it does take away the need for in-memory locking mechanisms, as are used in other languages to handle multiple threads of execution. This makes the JavaScript runtime a little easier to understand, and to work with.
    The traditional JavaScript mechanism for dealing with asynchronous requests is through the callback mechanism. This means that we provide a function, known as a callback function, to an asynchronous request, and this function will be executed once the asynchronous request has been processed.
    There have been a number of techniques introduced into the JavaScript language to help with writing asynchronous code. Each of these techniques has built upon the traditional callback mechanism that is typically used in JavaScript. One of the most popular techniques is known as Promises, which provides a simplified syntax for writing asynchronous code. The Promise mechanism also allows us to chain multiple asynchronous calls one after another, and this technique is known as fluent syntax. Another technique is known as async and await, where we mark certain functions as asynchronous, and can then use the await
  • Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    The duality between synchronous and asynchronous behavior is a fundamental concept in computer science—especially in a single-threaded event loop model such as JavaScript. Asynchronous behavior is borne out of the need to optimize for higher computational throughput in the face of high-latency operations. If it is feasible to run other instructions while a computation is completing and still maintain a stable system, then it is pragmatic to do so.
    Importantly, an asynchronous operation is not necessarily a computationally intensive or high-latency operation. It can be used anywhere it doesn't make sense to block a thread of execution to wait for the asynchronous behavior to occur.

    Synchronous vs. Asynchronous JavaScript

    Synchronous behavior is analogous to sequential processor instructions in memory. Each instruction is executed strictly in the order in which it appears, and each is also capable of immediately retrieving information that is stored locally within the system (for example: in a processor register or in system memory). As a result, it is easy to reason about the program state (for example, the value of a variable) at any given point in code.
    A trivial example of this would be performing a simple arithmetic operation:
    let x = 3; x = x + 4;
    At each step in this program, it is possible to reason about the state of the program because execution will not proceed until the previous instruction is completed. When the last instruction completes, the computed value of x is immediately available for use.
    This JavaScript snippet is easy to reason about because it is not difficult to anticipate what low-level instructions this will be compiled to (from JavaScript to x86, for example). Presumably, the operating system will allocate some memory for a floating point number on the stack, perform an arithmetic operation on that value, and write the result to that allocated memory. All of these instructions exist serially inside a single thread of execution. At each point in the compiled low-level program, you are well-equipped to assert what can and cannot be known about the state of the system.
  • Mastering JavaScript Promises
    So far, we have seen how the asynchronous model is implemented in JavaScript. This is one core aspect of understanding that JavaScript has its own implementation for the asynchronous programming model, and it has employed much of the core concepts in the asynchronous programming model.
    • The asynchronous mode is very important. In the browser, a very time-consuming operation should be performed asynchronously, avoiding the browser unresponsive time; the best example is the Ajax operations.
    • On the server side, the asynchronous mode of execution since the environment is single threaded. So, if you allow synchronization to perform all http requests, server performance will decline sharply and will soon lose responsiveness.
    • These are simple reasons why implementation on JavaScript is widely accepted in modern applications on all ends of needs. Databases such as MongoDB, Node.js as Server Side JavaScript, Angular.js, and Express.js as frontend, and logic building tools are examples of how heavily JavaScript is implemented throughout the industry. Their stack is commonly refer red to as the MEAN stack (MongoDB, Angular.js, Express.js, and Node.js)
  • RxJS in Action
    eBook - ePub
    • Paul Daniels, Luis Atencio(Authors)
    • 2017(Publication Date)
    • Manning
      (Publisher)
    after it has completely loaded. This behavior is ideal because it frees up the application to make progress on other tasks such as loading the rest of a web page, as in this case. As you’ll see throughout this book, asynchronous code is a good design for I/O-bound work like fetching data from the web or a database. The reason this works is that I/O processes are typically much slower than any other type of instruction, so we allow them to run in the background because they’re not dependent on processor cycles to complete.
    Syntax check
    In the code sample in section 1.1.2 , the second parameter of ajax() is the callback function. In that code, as in many parts of the book, we use the ECMAScript 6 lambda expression syntax,
    [1 ]
    which offers a terser and more succinct way of invoking functions. Also called arrow functions, lambda expressions behave somewhat similarly to an anonymous function call, which you’re probably familiar with. The subtle difference has to do with what the keyword this refers to. On rare occasions, when the value of this is important, we’ll call it out in the text and switch to using an anonymous function expression.
    1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions .
    1.1.3. Understanding time and space
    Certainly, asynchronous functions allow us to stay responsive, but they come at a price. Where synchronous programs allow us to reason directly about the state of the application, asynchronous code forces us to reason about its future state. What does this mean? State can be understood simply as a snapshot of all the information stored into variables at any point in time. This information is created and manipulated via sequences of statements. Synchronous code can be thought of as an ordered, step-by-step execution of statements, as shown in figure 1.3
  • JavaScript Concurrency
    In this chapter, we introduced some motivations for concurrency in JavaScript. While synchronous JavaScript is easy to maintain and understand, asynchronous JavaScript code is inevitable on the web. So it's important to make concurrency our default assumption when writing JavaScript applications.
    There's two main types of concurrency we're interested in—asynchronous actions and parallel actions. Asynchronicity is about the time ordering of actions, which gives the impression that things are happening at the same time. Without this type of concurrency, the user experience would suffer greatly, because it would constantly be waiting on other actions to complete. Parallelism is another type of concurrency that solves a different type of problem, where we want to increase performance by computing results faster.
    Finally, we looked at the three principles of concurrency in JavaScript programming. The parallelize principle is about leveraging the multi-core CPUs found in modern systems. The synchronize principle is about creating abstractions that enable us to write concurrent code, hiding the concurrency mechanisms from our feature code. The conserve principle uses lazy evaluation to only compute what is needed and to avoid unnecessary memory allocations.
    In the next chapter, we'll turn our attention to the JavaScript execution environment. To be effective with JavaScript concurrency, we need a sound understanding of what's actually happening when our code is run.
    Passage contains an image

    Chapter 2. The JavaScript Execution Model

    The first chapter of this book explored the state of JavaScript concurrency. Generally speaking, dealing with concurrency in JavaScript applications is anything but a trivial matter. There's a lot to think about when writing concurrent JavaScript code, and the kind of solutions that we come up with are often unorthodox. There's a lot of callbacks, and wading through all of them is enough to drive a person insane. We also caught a glimpse of how our pattern of writing concurrent JavaScript code has started to change with existing concurrency components. Web workers have started to mature, and JavaScript language concurrency constructs have only just been introduced.
  • The TypeScript Workshop
    eBook - ePub

    The TypeScript Workshop

    A practical guide to confident, effective TypeScript programming

    • Ben Grynhaus, Jordan Hudgens, Rayon Hunte, Matt Morgan, Wekoslav Stefanovski(Authors)
    • 2021(Publication Date)
    • Packt Publishing
      (Publisher)
    setTimeout function. The simplest equivalent code would be the following:
    console.log("We will wait 10 s"); setTimeout(() => {     console.log("... 10 seconds later");     setTimeout(() => {         console.log("... 15 more seconds later");     }, 15000); }, 10000);
    It's obvious that this code is much more complex than the C# equivalent, but the advantage that we get is that this code is non-blocking. In the 25 total seconds that this code is executing, our web page can do everything it needs to do. It can respond to events, the images can load and display, we can resize the window, scroll the text – basically, the application will resume the normal and expected functionalities.
    Note that while it's possible to block the JavaScript execution with some special synchronous code, it's not easy to do it. When it does actually happen, the browser can detect that it did happen and terminate the offending page:
    Figure 10.1: Unresponsive page

    Executing JavaScript

    When a JavaScript execution environment, such as a node or a browser loads a JavaScript file, it parses it and then runs it. All the functions that are defined in a JavaScript file are registered, and all the code that is not in a function is executed. The order of the execution is according to the code's position in the file. So, consider a file having the following code:
    console.log("First"); console.log("Second"); The console will always display this: First Second
    The order of the output cannot be changed, without changing the code itself. This is because the line with First will be executed completely – always – and then, and only then, will the line with Second
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.