One place for hosting & domains

      Understanding the Event Loop, Callbacks, Promises, and Async/Await in JavaScript


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      In the early days of the internet, websites often consisted of static data in an HTML page. But now that web applications have become more interactive and dynamic, it has become increasingly necessary to do intensive operations like make external network requests to retrieve API data. To handle these operations in JavaScript, a developer must use asynchronous programming techniques.

      Since JavaScript is a single-threaded programming language with a synchronous execution model that processes one operation after another, it can only process one statement at a time. However, an action like requesting data from an API can take an indeterminate amount of time, depending on the size of data being requested, the speed of the network connection, and other factors. If API calls were performed in a synchronous manner, the browser would not be able to handle any user input, like scrolling or clicking a button, until that operation completes. This is known as blocking.

      In order to prevent blocking behavior, the browser environment has many Web APIs that JavaScript can access that are asynchronous, meaning they can run in parallel with other operations instead of sequentially. This is useful because it allows the user to continue using the browser normally while the asynchronous operations are being processed.

      As a JavaScript developer, you need to know how to work with asynchronous Web APIs and handle the response or error of those operations. In this article, you will learn about the event loop, the original way of dealing with asynchronous behavior through callbacks, the updated ECMAScript 2015 addition of promises, and the modern practice of using async/await.

      Note: This article is focused on client-side JavaScript in the browser environment. The same concepts are generally true in the Node.js environment, however Node.js uses its own C++ APIs as opposed to the browser’s Web APIs. For more information on asynchronous programming in Node.js, check out How To Write Asynchronous Code in Node.js.

      The Event Loop

      This section will explain how JavaScript handles asynchronous code with the event loop. It will first run through a demonstration of the event loop at work, and will then explain the two elements of the event loop: the stack and the queue.

      JavaScript code that does not use any asynchronous Web APIs will execute in a synchronous manner—one at a time, sequentially. This is demonstrated by this example code that calls three functions that each print a number to the console:

      // Define three example functions
      function first() {
        console.log(1)
      }
      
      function second() {
        console.log(2)
      }
      
      function third() {
        console.log(3)
      }
      

      In this code, you define three functions that print numbers with console.log().

      Next, write calls to the functions:

      // Execute the functions
      first()
      second()
      third()
      

      The output will be based on the order the functions were called—first(), second(), then third():

      Output

      1 2 3

      When an asynchronous Web API is used, the rules become more complicated. A built-in API that you can test this with is setTimeout, which sets a timer and performs an action after a specified amount of time. setTimeout needs to be asynchronous, otherwise the entire browser would remain frozen during the waiting, which would result in a poor user experience.

      Add setTimeout to the second function to simulate an asynchronous request:

      // Define three example functions, but one of them contains asynchronous code
      function first() {
        console.log(1)
      }
      
      function second() {
        setTimeout(() => {
          console.log(2)
        }, 0)
      }
      
      function third() {
        console.log(3)
      }
      

      setTimeout takes two arguments: the function it will run asynchronously, and the amount of time it will wait before calling that function. In this code you wrapped console.log in an anonymous function and passed it to setTimeout, then set the function to run after 0 milliseconds.

      Now call the functions, as you did before:

      // Execute the functions
      first()
      second()
      third()
      

      You might expect with a setTimeout set to 0 that running these three functions would still result in the numbers being printed in sequential order. But because it is asynchronous, the function with the timeout will be printed last:

      Output

      1 3 2

      Whether you set the timeout to zero seconds or five minutes will make no difference—the console.log called by asynchronous code will execute after the synchronous top-level functions. This happens because the JavaScript host environment, in this case the browser, uses a concept called the event loop to handle concurrency, or parallel events. Since JavaScript can only execute one statement at a time, it needs the event loop to be informed of when to execute which specific statement. The event loop handles this with the concepts of a stack and a queue.

      Stack

      The stack, or call stack, holds the state of what function is currently running. If you’re unfamiliar with the concept of a stack, you can imagine it as an array with “Last in, first out” (LIFO) properties, meaning you can only add or remove items from the end of the stack. JavaScript will run the current frame (or function call in a specific environment) in the stack, then remove it and move on to the next one.

      For the example only containing synchronous code, the browser handles the execution in the following order:

      • Add first() to the stack, run first() which logs 1 to the console, remove first() from the stack.
      • Add second() to the stack, run second() which logs 2 to the console, remove second() from the stack.
      • Add third() to the stack, run third() which logs 3 to the console, remove third() from the stack.

      The second example with setTimout looks like this:

      • Add first() to the stack, run first() which logs 1 to the console, remove first() from the stack.
      • Add second() to the stack, run second().
        • Add setTimeout() to the stack, run the setTimeout() Web API which starts a timer and adds the anonymous function to the queue, remove setTimeout() from the stack.
      • Remove second() from the stack.
      • Add third() to the stack, run third() which logs 3 to the console, remove third() from the stack.
      • The event loop checks the queue for any pending messages and finds the anonymous function from setTimeout(), adds the function to the stack which logs 2 to the console, then removes it from the stack.

      Using setTimeout, an asynchronous Web API, introduces the concept of the queue, which this tutorial will cover next.

      Queue

      The queue, also referred to as message queue or task queue, is a waiting area for functions. Whenever the call stack is empty, the event loop will check the queue for any waiting messages, starting from the oldest message. Once it finds one, it will add it to the stack, which will execute the function in the message.

      In the setTimeout example, the anonymous function runs immediately after the rest of the top-level execution, since the timer was set to 0 seconds. It’s important to remember that the timer does not mean that the code will execute in exactly 0 seconds or whatever the specified time is, but that it will add the anonymous function to the queue in that amount of time. This queue system exists because if the timer were to add the anonymous function directly to the stack when the timer finishes, it would interrupt whatever function is currently running, which could have unintended and unpredictable effects.

      Note: There is also another queue called the job queue or microtask queue that handles promises. Microtasks like promises are handled at a higher priority than macrotasks like setTimeout.

      Now you know how the event loop uses the stack and queue to handle the execution order of code. The next task is to figure out how to control the order of execution in your code. To do this, you will first learn about the original way to ensure asynchronous code is handled correctly by the event loop: callback functions.

      Callback Functions

      In the setTimeout example, the function with the timeout ran after everything in the main top-level execution context. But if you wanted to ensure one of the functions, like the third function, ran after the timeout, then you would have to use asynchronous coding methods. The timeout here can represent an asynchronous API call that contains data. You want to work with the data from the API call, but you have to make sure the data is returned first.

      The original solution to dealing with this problem is using callback functions. Callback functions do not have special syntax; they are just a function that has been passed as an argument to another function. The function that takes another function as an argument is called a higher-order function. According to this definition, any function can become a callback function if it is passed as an argument. Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.

      Here is a syntactic code example of a higher-order function and a callback:

      // A function
      function fn() {
        console.log('Just a function')
      }
      
      // A function that takes another function as an argument
      function higherOrderFunction(callback) {
        // When you call a function that is passed as an argument, it is referred to as a callback
        callback()
      }
      
      // Passing a function
      higherOrderFunction(fn)
      

      In this code, you define a function fn, define a function higherOrderFunction that takes a function callback as an argument, and pass fn as a callback to higherOrderFunction.

      Running this code will give the following:

      Output

      Just a function

      Let’s go back to the first, second, and third functions with setTimeout. This is what you have so far:

      function first() {
        console.log(1)
      }
      
      function second() {
        setTimeout(() => {
          console.log(2)
        }, 0)
      }
      
      function third() {
        console.log(3)
      }
      

      The task is to get the third function to always delay execution until after the asynchronous action in the second function has completed. This is where callbacks come in. Instead of executing first, second, and third at the top-level of execution, you will pass the third function as an argument to second. The second function will execute the callback after the asynchronous action has completed.

      Here are the three functions with a callback applied:

      // Define three functions
      function first() {
        console.log(1)
      }
      
      function second(callback) {
        setTimeout(() => {
          console.log(2)
      
          // Execute the callback function
          callback()
        }, 0)
      }
      
      function third() {
        console.log(3)
      }
      

      Now, execute first and second, then pass third as an argument to second:

      first()
      second(third)
      

      After running this code block, you will receive the following output:

      Output

      1 2 3

      First 1 will print, and after the timer completes (in this case, zero seconds, but you can change it to any amount) it will print 2 then 3. By passing a function as a callback, you’ve successfully delayed execution of the function until the asynchronous Web API (setTimeout) completes.

      The key takeaway here is that callback functions are not asynchronous—setTimeout is the asynchronous Web API responsible for handling asynchronous tasks. The callback just allows you to be informed of when an asynchronous task has completed and handles the success or failure of the task.

      Now that you have learned how to use callbacks to handle asynchronous tasks, the next section explains the problems of nesting too many callbacks and creating a “pyramid of doom.”

      Nested Callbacks and the Pyramid of Doom

      Callback functions are an effective way to ensure delayed execution of a function until another one completes and returns with data. However, due to the nested nature of callbacks, code can end up getting messy if you have a lot of consecutive asynchronous requests that rely on each other. This was a big frustration for JavaScript developers early on, and as a result code containing nested callbacks is often called the “pyramid of doom” or “callback hell.”

      Here is a demonstration of nested callbacks:

      function pyramidOfDoom() {
        setTimeout(() => {
          console.log(1)
          setTimeout(() => {
            console.log(2)
            setTimeout(() => {
              console.log(3)
            }, 500)
          }, 2000)
        }, 1000)
      }
      

      In this code, each new setTimeout is nested inside a higher order function, creating a pyramid shape of deeper and deeper callbacks. Running this code would give the following:

      Output

      1 2 3

      In practice, with real world asynchronous code, this can get much more complicated. You will most likely need to do error handling in asynchronous code, and then pass some data from each response onto the next request. Doing this with callbacks will make your code difficult to read and maintain.

      Here is a runnable example of a more realistic “pyramid of doom” that you can play around with:

      // Example asynchronous function
      function asynchronousRequest(args, callback) {
        // Throw an error if no arguments are passed
        if (!args) {
          return callback(new Error('Whoa! Something went wrong.'))
        } else {
          return setTimeout(
            // Just adding in a random number so it seems like the contrived asynchronous function
            // returned different data
            () => callback(null, {body: args + ' ' + Math.floor(Math.random() * 10)}),
            500,
          )
        }
      }
      
      // Nested asynchronous requests
      function callbackHell() {
        asynchronousRequest('First', function first(error, response) {
          if (error) {
            console.log(error)
            return
          }
          console.log(response.body)
          asynchronousRequest('Second', function second(error, response) {
            if (error) {
              console.log(error)
              return
            }
            console.log(response.body)
            asynchronousRequest(null, function third(error, response) {
              if (error) {
                console.log(error)
                return
              }
              console.log(response.body)
            })
          })
        })
      }
      
      // Execute 
      callbackHell()
      

      In this code, you must make every function account for a possible response and a possible error, making the function callbackHell visually confusing.

      Running this code will give you the following:

      Output

      First 9 Second 3 Error: Whoa! Something went wrong. at asynchronousRequest (<anonymous>:4:21) at second (<anonymous>:29:7) at <anonymous>:9:13

      This way of handling asynchronous code is difficult to follow. As a result, the concept of promises was introduced in ES6. This is the focus of the next section.

      Promises

      A promise represents the completion of an asynchronous function. It is an object that might return a value in the future. It accomplishes the same basic goal as a callback function, but with many additional features and a more readable syntax. As a JavaScript developer, you will likely spend more time consuming promises than creating them, as it is usually asynchronous Web APIs that return a promise for the developer to consume. This tutorial will show you how to do both.

      Creating a Promise

      You can initialize a promise with the new Promise syntax, and you must initialize it with a function. The function that gets passed to a promise has resolve and reject parameters. The resolve and reject functions handle the success and failure of an operation, respectively.

      Write the following line to declare a promise:

      // Initialize a promise
      const promise = new Promise((resolve, reject) => {})
      

      If you inspect the initialized promise in this state with your web browser’s console, you will find it has a pending status and undefined value:

      Output

      __proto__: Promise [[PromiseStatus]]: "pending" [[PromiseValue]]: undefined

      So far, nothing has been set up for the promise, so it’s going to sit there in a pending state forever. The first thing you can do to test out a promise is fulfill the promise by resolving it with a value:

      const promise = new Promise((resolve, reject) => {
        resolve('We did it!')
      })
      

      Now, upon inspecting the promise, you’ll find that it has a status of fulfilled, and a value set to the value you passed to resolve:

      Output

      __proto__: Promise [[PromiseStatus]]: "fulfilled" [[PromiseValue]]: "We did it!"

      As stated in the beginning of this section, a promise is an object that may return a value. After being successfully fulfilled, the value goes from undefined to being populated with data.

      A promise can have three possible states: pending, fulfilled, and rejected.

      • Pending – Initial state before being resolved or rejected
      • Fulfilled – Successful operation, promise has resolved
      • Rejected – Failed operation, promise has rejected

      After being fulfilled or rejected, a promise is settled.

      Now that you have an idea of how promises are created, let’s look at how a developer may consume these promises.

      Consuming a Promise

      The promise in the last section has fulfilled with a value, but you also want to be able to access the value. Promises have a method called then that will run after a promise reaches resolve in the code. then will return the promise’s value as a parameter.

      This is how you would return and log the value of the example promise:

      promise.then((response) => {
        console.log(response)
      })
      

      The promise you created had a [[PromiseValue]] of We did it!. This value is what will be passed into the anonymous function as response:

      Output

      We did it!

      So far, the example you created did not involve an asynchronous Web API—it only explained how to create, resolve, and consume a native JavaScript promise. Using setTimeout, you can test out an asynchronous request.

      The following code simulates data returned from an asynchronous request as a promise:

      const promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve('Resolving an asynchronous request!'), 2000)
      })
      
      // Log the result
      promise.then((response) => {
        console.log(response)
      })
      

      Using the then syntax ensures that the response will be logged only when the setTimeout operation is completed after 2000 milliseconds. All this is done without nesting callbacks.

      Now after two seconds, it will resolve the promise value and it will get logged in then:

      Output

      Resolving an asynchronous request!

      Promises can also be chained to pass along data to more than one asynchronous operation. If a value is returned in then, another then can be added that will fulfill with the return value of the previous then:

      // Chain a promise
      promise
        .then((firstResponse) => {
          // Return a new value for the next then
          return firstResponse + ' And chaining!'
        })
        .then((secondResponse) => {
          console.log(secondResponse)
        })
      

      The fulfilled response in the second then will log the return value:

      Output

      Resolving an asynchronous request! And chaining!

      Since then can be chained, it allows the consumption of promises to appear more synchronous than callbacks, as they do not need to be nested. This will allow for more readable code that can be maintained and verified easier.

      Error Handling

      So far, you have only handled a promise with a successful resolve, which puts the promise in a fulfilled state. But frequently with an asynchronous request you also have to handle an error—if the API is down, or a malformed or unauthorized request is sent. A promise should be able to handle both cases. In this section, you will create a function to test out both the success and error case of creating and consuming a promise.

      This getUsers function will pass a flag to a promise, and return the promise:

      function getUsers(onSuccess) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            // Handle resolve and reject in the asynchronous API
          }, 1000)
        })
      }
      

      Set up the code so that if onSuccess is true, the timeout will fulfill with some data. If false, the function will reject with an error:

      function getUsers(onSuccess) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            // Handle resolve and reject in the asynchronous API
            if (onSuccess) {
              resolve([
                {id: 1, name: 'Jerry'},
                {id: 2, name: 'Elaine'},
                {id: 3, name: 'George'},
              ])
            } else {
              reject('Failed to fetch data!')
            }
          }, 1000)
        })
      }
      

      For the successful result, you return JavaScript objects that represent sample user data.

      In order to handle the error, you will use the catch instance method. This will give you a failure callback with the error as a parameter.

      Run the getUser command with onSuccess set to false, using the then method for the success case and the catch method for the error:

      // Run the getUsers function with the false flag to trigger an error
      getUsers(false)
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {
          console.error(error)
        })
      

      Since the error was triggered, the then will be skipped and the catch will handle the error:

      Output

      Failed to fetch data!

      If you switch the flag and resolve instead, the catch will be ignored, and the data will return instead:

      // Run the getUsers function with the true flag to resolve successfully
      getUsers(true)
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {
          console.error(error)
        })
      

      This will yield the user data:

      Output

      (3) [{…}, {…}, {…}] 0: {id: 1, name: "Jerry"} 1: {id: 2, name: "Elaine"} 3: {id: 3, name: "George"}

      For reference, here is a table with the handler methods on Promise objects:

      Method Description
      then() Handles a resolve. Returns a promise, and calls onFulfilled function asynchronously
      catch() Handles a reject. Returns a promise, and calls onRejected function asynchronously
      finally() Called when a promise is settled. Returns a promise, and calls onFinally function asynchronously

      Promises can be confusing, both for new developers and experienced programmers that have never worked in an asynchronous environment before. However as mentioned, it is much more common to consume promises than create them. Usually, a browser’s Web API or third party library will be providing the promise, and you only need to consume it.

      In the final promise section, this tutorial will cite a common use case of a Web API that returns promises: the Fetch API.

      Using the Fetch API with Promises

      One of the most useful and frequently used Web APIs that returns a promise is the Fetch API, which allows you to make an asynchronous resource request over a network. fetch is a two-part process, and therefore requires chaining then. This example demonstrates hitting the GitHub API to fetch a user’s data, while also handling any potential error:

      // Fetch a user from the GitHub API
      fetch('https://api.github.com/users/octocat')
        .then((response) => {
          return response.json()
        })
        .then((data) => {
          console.log(data)
        })
        .catch((error) => {
          console.error(error)
        })
      

      The fetch request is sent to the https://api.github.com/users/octocat URL, which asynchronously waits for a response. The first then passes the response to an anonymous function that formats the response as JSON data, then passes the JSON to a second then that logs the data to the console. The catch statement logs any error to the console.

      Running this code will yield the following:

      Output

      login: "octocat", id: 583231, avatar_url: "https://avatars3.githubusercontent.com/u/583231?v=4" blog: "https://github.blog" company: "@github" followers: 3203 ...

      This is the data requested from https://api.github.com/users/octocat, rendered in JSON format.

      This section of the tutorial showed that promises incorporate a lot of improvements for dealing with asynchronous code. But, while using then to handle asynchronous actions is easier to follow than the pyramid of callbacks, some developers still prefer a synchronous format of writing asynchronous code. To address this need, ECMAScript 2016 (ES7) introduced async functions and the await keyword to make working with promises easier.

      Async Functions with async/await

      An async function allows you to handle asynchronous code in a manner that appears synchronous. async functions still use promises under the hood, but have a more traditional JavaScript syntax. In this section, you will try out examples of this syntax.

      You can create an async function by adding the async keyword before a function:

      // Create an async function
      async function getUser() {
        return {}
      }
      

      Although this function is not handling anything asynchronous yet, it behaves differently than a traditional function. If you execute the function, you’ll find that it returns a promise with a [[PromiseStatus]] and [[PromiseValue]] instead of a return value.

      Try this out by logging a call to the getUser function:

      console.log(getUser())
      

      This will give the following:

      Output

      __proto__: Promise [[PromiseStatus]]: "fulfilled" [[PromiseValue]]: Object

      This means you can handle an async function with then in the same way you could handle a promise. Try this out with the following code:

      getUser().then((response) => console.log(response))
      

      This call to getUser passes the return value to an anonymous function that logs the value to the console.

      You will receive the following when you run this program:

      Output

      {}

      An async function can handle a promise called within it using the await operator. await can be used within an async function and will wait until a promise settles before executing the designated code.

      With this knowledge, you can rewrite the Fetch request from the last section using async/await as follows:

      // Handle fetch with async/await
      async function getUser() {
        const response = await fetch('https://api.github.com/users/octocat')
        const data = await response.json()
      
        console.log(data)
      }
      
      // Execute async function
      getUser()
      

      The await operators here ensure that the data is not logged before the request has populated it with data.

      Now the final data can be handled inside the getUser function, without any need for using then. This is the output of logging data:

      Output

      login: "octocat", id: 583231, avatar_url: "https://avatars3.githubusercontent.com/u/583231?v=4" blog: "https://github.blog" company: "@github" followers: 3203 ...

      Note: In many environments, async is necessary to use await—however, some new versions of browsers and Node allow using top-level await, which allows you to bypass creating an async function to wrap the await in.

      Finally, since you are handling the fulfilled promise within the asynchronous function, you can also handle the error within the function. Instead of using the catch method with then, you will use the try/catch pattern to handle the exception.

      Add the following highlighted code:

      // Handling success and errors with async/await
      async function getUser() {
        try {
          // Handle success in try
          const response = await fetch('https://api.github.com/users/octocat')
          const data = await response.json()
      
          console.log(data)
        } catch (error) {
          // Handle error in catch
          console.error(error)
        }
      }
      

      The program will now skip to the catch block if it receives an error and log that error to the console.

      Modern asynchronous JavaScript code is most often handled with async/await syntax, but it is important to have a working knowledge of how promises work, especially as promises are capable of additional features that cannot be handled with async/await, like combining promises with Promise.all().

      Note: async/await can be reproduced by using generators combined with promises to add more flexibility to your code. To learn more, check out our Understanding Generators in JavaScript tutorial.

      Conclusion

      Because Web APIs often provide data asynchronously, learning how to handle the result of asynchronous actions is an essential part of being a JavaScript developer. In this article, you learned how the host environment uses the event loop to handle the order of execution of code with the stack and queue. You also tried out examples of three ways to handle the success or failure of an asynchronous event, with callbacks, promises, and async/await syntax. Finally, you used the Fetch Web API to handle asynchronous actions.

      For more information about how the browser handles parallel events, read Concurrency model and the event loop on the Mozilla Developer Network. If you’d like to learn more about JavaScript, return to our How To Code in JavaScript series.



      Source link

      So konfigurieren Sie Apache HTTP mit MPM Event und PHP-FPM unter Ubuntu 18.04


      Der Autor hat den COVID-19 Relief Fund dazu ausgewählt, eine Spende im Rahmen des Programms Write for DOnations zu erhalten.

      Einführung

      Der Apache-HTTP-Webserver wurde im Laufe der Jahre weiterentwickelt, damit er in verschiedenen Umgebungen arbeitet und verschiedene Anforderungen erfüllt. Ein wichtiges Problem, das Apache HTTP wie jeder andere Webserver auch lösen muss, ist die Handhabung verschiedener Prozesse bei der Bearbeitung von http-basierten Anfragen. Dazu zählt das Öffnen eines Sockets, das die Anforderung verarbeitet, das Offenhalten der Verbindung für eine bestimmte Zeit, die Handhabung neuer Ereignisse, die während dieser Verbindung eintreten und die Rückgabe des produzierten Contents durch ein Programm, dass in einer bestimmten Sprache geschrieben wurde (wie PHP, Perl oder Python). Diese Aufgaben werden von einem Multi-Processing-Module (MPM) ausgeführt und gesteuert.

      Apache HTTP ist mit drei verschiedenen MPM ausgestattet:

      • Prefork: Für jede eingehende Verbindung, die den Server erreicht, wird ein neuer Vorgang erstellt. Jeder Vorgang ist isoliert von den anderen und es wird kein Speicher zwischen ihnen geteilt, selbst dann, wenn sie in der Ausführung identische Anrufe an einem bestimmten Punkt ausführen. Auf diese Weise können Sie mit Bibliotheken verknüpfte Anwendungen, die Thread-Ausführungen nicht unterstützen, sicher ausführen – meist ältere Anwendungen oder Bibliotheken.
      • Worker: Ein Elternprozess ist für das Starten eines Bündels von Kindprozessen verantwortlich, von denen einige neu eingehende Verbindungen erfassen und andere den angeforderten Content bereitstellen. Für jeden Prozess gibt es einen dazugehörigen Thread (ein einzelner Thread kann jeweils eine Verbindung verwalten), sodass ein Prozess mit mehreren Anfragen gleichzeitig umgehen kann. Diese Methode für die Handhabung von Verbindungen fördert eine bessere Ressourcennutzung und gewährleistet die Aufrechterhaltung der Stabilität. Das ist auf das Bündel von verfügbaren Prozessen zurückzuführen, bei denen oft frei verfügbare Threads bereitstehen, die neue Verbindungen sofort bedienen können.
      • Event: Basierend auf Worker geht dieses MPM noch einen Schritt weiter, indem es die Art und Weise optimiert, wie der Elternprozess Aufgaben für die Kindprozesse und für die Threads, die damit verknüpft sind, vorgibt. Eine Verbindung bleibt für 5 Sekunden standardmäßig geöffnet und schließt sich bei jedem neuen Ereignis, das eintritt; das ist der Standardwert für die Keep-Alive-Anweisung, der den mit ihm verknüpften Thread beibehält. Das Event MPM ermöglicht dem Prozess das Verwalten von Threads, damit einige Threads für die Verwaltung neuer eingehender Verbindungen bereitstehen, während andere weiterhin mit den Live-Verbindungen verknüpft sind. Die Ressourcennutzung und Leistungsfähigkeit wird dadurch verbessert, dass die den Threads zugewiesenen Aufgaben neu verteilt werden können.

      Mit dem MPM Event-Modul ist ein schnelles Multi-Processing-Modul auf dem Apache-HTTP-Webserver verfügbar.

      PHP-FPM ist der FastCGI-Prozessmanager für PHP. Das FastCGI-Protokoll basiert auf dem Common Gateway Interface (CGI), einem Protokoll, das zwischen Anwendungen und Webservern wie Apache HTTP steht. Dadurch können Entwickler Anwendungen schreiben, ohne das Verhalten der Webserver berücksichtigen zu müssen. Die Programme führen ihre Prozesse unabhängig aus und übergeben ihr Produkt über dieses Protokoll an den Webserver. Jede neue Verbindung, die von einer Anwendung verarbeitet werden muss, erstellt einen neuen Prozess.

      Durch die Kombination von MPM Event in Apache HTTP mit dem PHP FastCGI-Prozessmanager (PHP-FPM) kann eine Website schneller laden und mehr gleichzeitige Verbindungen mit weniger Ressourcen verarbeiten.

      In diesem Tutorial verbessern Sie die Leistung des LAMP-Stacks, indem Sie das standardmäßige Multi-Processing-Module von Prefork auf Event umstellen und den PHP-FPM-Prozessmanager für die Handhabung des PHP-Codes nutzen anstelle des klassischen mod_php in Apache HTTP.

      Voraussetzungen

      Bevor Sie diese Anleitung beginnen, benötigen Sie Folgendes:

      Schritt 1 — Umstellen des Multi-Processing-Module

      Ubuntu übernimmt Skripte, um Apache-HTTP-Module über die eigene übergeordnete Distribution Debian zu aktivieren oder zu deaktivieren. Sie werden dieses Toolset in diesem Schritt verwenden, um das Prefork-Modul zu deaktivieren und das Event-Modul zu aktivieren.

      In diesem Schritt halten Sie Apache HTTP an, deaktivieren das Modul PHP 7.2, das mit dem Prefork-Modul verknüpft ist, und deaktivieren anschließend Prefork, um das Event-Modul unmittelbar aktivieren zu können.

      Zuerst halten Sie den Apache-HTTP-Dienst an:

      • sudo systemctl stop apache2

      Nun können Sie das Modul PHP 7.2 deaktivieren, das mit dem Prefork-Modul in Verbindung steht:

      Deaktivieren Sie dann das Prefork MPM-Modul:

      • sudo a2dismod mpm_prefork

      Nun Aktivieren Sie das Event MPM-Modul:

      Sie haben das MPM von Prefork auf Event umgestellt und die Modulverbindung PHP 7.2 zwischen PHP und Apache HTTP entfernt. Im nächsten Schritt installieren Sie das php-fpm-Modul sowie die verwandten Bibliotheken und Proxy-Module. Sie konfigurieren Apache HTTP so, dass es auch mit PHP kommunizieren kann.

      Schritt 2 — Konfigurieren von Apache HTTP für die Nutzung des FastCGI-Prozesses

      In dieser Phase haben Sie die Verarbeitung von Verbindungen durch Apache HTTP umgestellt, indem Sie sie von dem Prefork-MPM auf Event verlagert haben. Im Zuge dessen haben Sie jedoch das PHP-Modul deaktiviert, das Apache HTTP mit jedem Programm verbunden hatte, das mit PHP ausgeführt wird.

      In diesem Schritt installieren Sie den PHP-FPM-Prozessor, damit Apache HTTP wieder PHP-Programme verarbeiten kann. Außerdem installieren Sie die Abhängigkeitsbibliotheken und aktivieren die Module, damit beide reibungslos und schneller zusammenarbeiten können als zuvor.

      Installieren Sie zuerst php-fpm. Der folgende Befehl installiert das PHP-FPM und aktiviert automatisch den Dienst php7.2-fpm, der in systemd integriert ist, sodass der Dienst beim Booten gestartet wird:

      Apache HTTP und PHP benötigen für die Kommunikation eine Bibliothek, die diese Funktion ermöglicht. Nun installieren Sie libapache2-mod-fcgid, das als Schnittstelle zwischen Programmen mit Webservern dient und Apache-HTTP-spezifisch ist. Diese Kommunikation erfolgt über ein UNIX-Socket.

      Installieren Sie diese Bibliothek:

      • sudo apt install libapache2-mod-fcgid

      Sie haben php-fpm und das libapache2-mod-fcgid installiert, aber noch keines davon aktiviert.

      Aktivieren Sie zuerst das php-fpm-Modul mit folgendem Befehl:

      Aktivieren Sie in einem zweiten Schritt das Apache HTTP-Proxy-Modul:

      Aktivieren Sie in einem dritten Schritt das FastCGI-Proxy-Modul auf Apache HTTP:

      Hinweis: Sie können die Konfiguration dieser Interaktion zwischen PHP-Programmen und Apache HTTP über einen UNIX-Socket mit Folgendem lesen:

      • cat /etc/apache2/conf-enabled/php7.2-fpm.conf

      Nun wurden alle Vorkehrungen getroffen, damit Sie Apache HTTP starten können. Führen Sie eine Konfigurationsüberprüfung durch:

      • sudo apachectl configtest

      Output

      Syntax OK

      Danach können Sie mit dem Neustart von Apache HTTP fortfahren, da es beim Installieren der FastCGI-Bibliothek libapache2-mod-fcgid automatisch gestartet wurde:

      • sudo systemctl restart apache2

      Sie haben das php-fpm-Modul installiert und Apache HTTP so konfiguriert, dass es damit funktioniert. Zudem haben Sie ermöglicht, dass die erforderlichen Module für das FastCGI-Protokoll funktionieren, und die entsprechenden Dienste gestartet.

      Nachdem Apache das Event MPM-Modul aktiviert hat und PHP-FPM verfügbar ist und ausgeführt wird, ist es an der Zeit sicherzustellen, das alles wie geplant funktioniert.

      Schritt 3 — Testen Ihrer Konfiguration

      Führen Sie einige Tests aus, um zu prüfen, ob die Konfigurationsänderungen angewendet wurden. Beim ersten Test wird geprüft, welches Multi-Processing-Modul Apache HTTP verwendet. Beim zweiten Test wird sichergestellt, dass PHP den FPM-Manager verwendet.

      Überprüfen Sie den Apache-HTTP-Server, indem Sie den folgenden Befehl ausführen:

      • sudo apachectl -M | grep 'mpm'

      Sie erhalten folgende Ausgabe:

      Output

      mpm_event_module (shared)

      Für das Proxy-Modul und FastCGI können Sie diese Prozedur wiederholen:

      • sudo apachectl -M | grep 'proxy'

      Die Ausgabe zeigt Folgendes:

      Output

      proxy_module (shared) proxy_fcgi_module (shared)

      Wenn Sie die gesamte Liste der Module sehen möchten, können Sie den zweiten Teil des Befehls nach -M entfernen.

      Nun ist es Zeit zu prüfen, ob PHP den FastCGI-Prozessmanager verwendet. Dazu schreiben Sie ein kleines PHP-Skript, das Ihnen alle Informationen zeigt, die mit PHP in Verbindung stehen.

      Führen Sie den folgenden Befehl aus, um eine Datei zu schreiben, deren Name wie folgt lautet:

      • sudo nano /var/www/your_domain/info.php

      Fügen Sie den folgenden Inhalt in die Datei info.php ein:

      info.php

      <?php phpinfo(); ?>
      

      Rufen Sie nun die URL Ihres Servers auf und fügen Sie info.php am Ende hinzu: http://your_domain/info.php.

      Der Server-API-Eintrag lautet FPM/FastCGI.

      PHP Screen the Server API entry FPM/FastCGI

      Löschen Sie die Datei info.php nach diesem Test, damit keine Informationen über den Server veröffentlicht werden:

      • sudo rm /var/www/yourdomain.com/info.php

      Sie haben den Betriebszustand des MPM-Moduls und der Module, die für die Handhabung von FastCGI zuständig sind, sowie die Handhabung des PHP-Codes überprüft.

      Zusammenfassung

      Sie haben Ihren ursprünglichen LAMP-Stack optimiert, sodass sich die Anzahl der Verbindungen zur Erstellung neuer Apache HTTP-Prozesse erhöht hat, PHP-FPM den PHP-Code effizienter verwaltet und sich die Ressourcennutzung insgesamt verbessert.

      Weitere Informationen zu den verschiedenen Modulen und verwandten Projekten finden Sie in der Projekt-Dokumentation zum Apache HTTP-Server.



      Source link

      Using Event Emitters in Node.js


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Event emitters are objects in Node.js that trigger an event by sending a message to signal that an action was completed. JavaScript developers can write code that listens to events from an event emitter, allowing them to execute functions every time those events are triggered. In this context, events are composed of an identifying string and any data that needs to be passed to the listeners.

      Typically in Node.js, when we want to have an action occur upon completion of another action, we use asynchronous programming techniques like nesting callbacks or chaining promises. However, these techniques tightly couple the triggering action and the resulting action, making it difficult to modify the resulting action in the future. Event emitters provide a different way to structure this relationship: the publish-subscribe pattern. In this software architecture pattern, a publisher (the event emitter) sends a message (an event), and a subscriber receives the event and performs an action. The power of this pattern is that the publisher does not need to know about the subscribers. A publisher publishes a message, and it’s up to the subscribers to react to it in their respective ways. If we wanted to change the behavior of our application, we could adjust how the subscribers react to the events without having to change the publisher.

      In this article, we will create an event listener for a TicketManager JavaScript class that allows a user to buy tickets. We will set up listeners for the buy event, which will trigger every time a ticket is bought. This process will also show how to manage erroneous events from the emitter and how to manage event subscribers.

      Prerequisites

      Step 1 — Emitting Events

      In this step, we’ll explore the two most common ways to create an event emitter in Node.js. The first is to use an event emitter object directly, and the second is to create an object that extends the event emitter object.

      Deciding which one to use depends on how coupled your events are to the actions of your objects. If the events you want to emit are an effect of an object’s actions, you would likely extend from the event emitter object to have access to its functions for convenience. If the events you want to emit are independent of your business objects or are a result of actions from many business objects, you would instead create an independent event emitter object that’s referenced by your objects.

      Let’s begin by creating a standalone, event-emitting object. We’ll begin by creating a folder to store all of our code. In your terminal, make a new folder called event-emitters:

      Then enter that folder:

      Open the first event emitter, firstEventEmitter.js, in a text editor. We will use nano as it’s available in the terminal:

      • nano firstEventEmitter.js

      In Node.js, we emit events via the EventEmitter class. This class is part of the events module. Let’s begin by first loading the events module in our file by adding the following line:

      event-emitters/firstEventEmitter.js

      const { EventEmitter } = require("events");
      

      With the class imported, we can use it to create a new object instance from it:

      event-emitters/firstEventEmitter.js

      const { EventEmitter } = require("events");
      
      const firstEmitter = new EventEmitter();
      

      Let’s emit an event by adding the following highlighted line at the end of firstEventEmitter.js:

      event-emitters/firstEventEmitter.js

      const { EventEmitter } = require("events");
      
      const firstEmitter = new EventEmitter();
      
      
      firstEmitter.emit("My first event");
      

      The emit() function is used to fire events. We need to pass the name of the event to it as a string. We can add any number of arguments after the event name. Events with just a name are fairly limited; the other arguments allow us to send data to our listeners. When we set up our ticket manager, our events will pass data about the purchase when it happens. Keep the name of the event in mind, because event listeners will identify it by this name.

      Note: While we don’t capture it in this example, the emit() function returns true if there are listeners for the event. If there are no listeners for an event, it returns false.

      Let’s run this file to see what happens. Save and exit nano, then execute the file with the node command:

      • node firstEventEmitter.js

      When the script finishes its execution, you will see no output in the terminal. That’s because we do not log any messages in firstEventEmitter.js and there’s nothing that listens to the event that was sent. The event is emitted, but nothing acts on these events.

      Let’s work toward seeing a more complete example of publishing, listening to, and acting upon events. We’ll do this by creating a ticket manager example application. The ticket manager will expose a function to buy tickets. When a ticket is bought, an event will be sent with details of the purchaser. Later, we’ll create another Node.js module to simulate an email being sent to the purchaser’s email confirming the purchase.

      Let’s begin by creating our ticket manager. It will extend the EventEmitter class so that we don’t have to create a separate event emitter object to emit events.

      In the same working directory, create and open a new file called ticketManager.js:

      As with the first event emitter, we need to import the EventEmitter class from the events module. Put the following code at the beginning of the file:

      event-emitters/ticketManager.js

      const EventEmitter = require("events");
      

      Now, make a new TicketManager class that will soon define the method for ticket purchases:

      event-emitters/ticketManager.js

      const EventEmitter = require("events");
      
      class TicketManager extends EventEmitter {}
      

      In this case, the TicketManager class extends the EventEmitter class. This means that the TicketManager class inherits the methods and properties of the EventEmitter class. This is how it gets access to the emit() method.

      In our ticket manager, we want to provide the initial supply of tickets that can be purchased. We’ll do this by accepting the initial supply in our constructor(), a special function that’s called when a new object of a class is made. Add the following constructor to the TicketManager class:

      event-emitters/ticketManager.js

      const EventEmitter = require("events");
      
      class TicketManager extends EventEmitter {
          constructor(supply) {
              super();
              this.supply = supply;
          }
      }
      

      The constructor has one supply argument. This is a number detailing the initial supply of tickets we can sell. Even though we declared that TicketManager is a child class of EventEmitter, we still need to call super() to get access to the methods and properties of EventEmitter. The super() function calls the constructor of the parent function, which in this case is EventEmitter.

      Finally, we create a supply property for the object with this.supply and give it the value passed in by the constructor.

      Now, let’s add a buy() method that will be called when a ticket is purchased. This method will decrease the supply by one and emit an event with the purchase data.

      Add the buy() method as follows:

      event-emitters/ticketManager.js

      const EventEmitter = require("events");
      
      class TicketManager extends EventEmitter {
          constructor(supply) {
              super();
              this.supply = supply;
          }
      
          buy(email, price) {
              this.supply--;
              this.emit("buy", email, price, Date.now());
          }
      }
      

      In the buy() function, we take the purchaser’s email address and the price they paid for the ticket. We then decrease the supply of tickets by one. We end by emitting a buy event. This time, we emit an event with extra data: the email and price that were passed in the function as well as a timestamp of when the purchase was made.

      So that our other Node.js modules can use this class, we need to export it. Add this line at the end of the file:

      event-emitters/ticketManager.js

      ...
      
      module.exports = TicketManager
      

      Save and exit the file.

      We’ve finished our setup for the event emitter TicketManager. Now that we’ve put things in place to push events, we can move on to reading and processing those events. To do that, we will create event listeners in the next step.

      Step 2 — Listening for Events

      Node.js allows us to add a listener for an event with the on() function of an event emitter object. This listens for a particular event name and fires a callback when the event is triggered. Adding a listener typically looks like this:

      eventEmitter.on(event_name, callback_function) {
          action
      }
      

      Note:: Node.js aliases the on() method with addListener(). They perform the same task. In this tutorial, we will continue to use on().

      Let’s get some first-hand experience with listening to our first event. Create a new file called firstListener.js:

      As a demonstration of how the on() function works, let’s log a simple message upon receiving our first event.

      First, let’s import TicketManager into our new Node.js module. Add the following code into firstListener.js:

      event-emitters/firstListener.js

      const TicketManager = require("./ticketManager");
      
      const ticketManager = new TicketManager(10);
      

      Recall that TicketManager objects need their initial supply of tickets when created. This is why we pass the 10 argument.

      Now let’s add our first Node.js event listener. It will listen to the buy event. Add the following highlighted code:

      event-emitters/firstListener.js

      const TicketManager = require("./ticketManager");
      
      const ticketManager = new TicketManager(10);
      
      ticketManager.on("buy", () => {
          console.log("Someone bought a ticket!");
      });
      

      To add a new listener, we used the on() function that’s a part of the ticketManager object. The on() method is available to all event emitter objects, and since TicketManager inherits from the EventEmitter class, this method is available on all of the TicketManager instance objects.

      The second argument to the on() method is a callback function, written as an arrow function. The code in this function is run after the event is emitted. In this case, we log "Someone bought a ticket!" to the console if a buy event is emitted.

      Now that we set up a listener, let’s use the buy() function so that the event will be emitted. At the end of your file add this:

      event-emitters/firstListener.js

      ...
      
      ticketManager.buy("test@email.com", 20);
      

      This performs the buy method with a user email of test@email.com and a ticket price of 20.

      Save and exit the file.

      Now run this script with node:

      Your console will display this:

      Output

      Someone bought a ticket!

      Your first event listener worked. Let’s see what happens if we buy multiple tickets. Re-open your firstListener.js in your text editor:

      At the end of the file, make another call to the buy() function:

      event-emitters/firstListener.js

      ...
      
      ticketManager.buy("test@email.com", 20);
      ticketManager.buy("test@email.com", 20);
      

      Save and exit the file. Let’s run the script with Node.js to see what happens:

      Your console will display this:

      Output

      Someone bought a ticket! Someone bought a ticket!

      Since the buy() function was called twice, two buy events were emitted. Our listener picked up both.

      Sometimes we’re only interested in listening to the first time an event was fired, as opposed to all the times it’s emitted. Node.js provides an alternative to on() for this case with the once() function.

      Like on(), the once() function accepts the event name as its first argument, and a callback function that’s called when the event is fired as its second argument. Under the hood, when the event is emitted and received by a listener that uses once(), Node.js automatically removes the listener and then executes the code in the callback function.

      Let’s see once() in action by editing firstListener.js:

      At the end of the file, add a new event listener using once() like the following highlighted lines:

      event-emitters/firstListener.js

      const TicketManager = require("./ticketManager");
      
      const ticketManager = new TicketManager(10);
      
      ticketManager.on("buy", () => {
              console.log("Someone bought a ticket!");
      });
      
      ticketManager.buy("test@email.com", 20);
      ticketManager.buy("test@email.com", 20);
      
      ticketManager.once("buy", () => {
          console.log("This is only called once");
      });
      

      Save and exit the file and run this program with node:

      The output is the same as the last time:

      Output

      Someone bought a ticket! Someone bought a ticket!

      While we added a new event listener with once(), it was added after the buy events were emitted. Because of this, the listener didn’t detect these two events. You can’t listen for events that already happened in the past. When you add a listener you can only capture events that come after.

      Let’s add a couple more buy() function calls so we can confirm that the once() listener only reacts one time. Open firstListener.js in your text editor like before:

      Add the following calls at the end of the file:

      event-emitters/firstListener.js

      ...
      
      ticketManager.once("buy", () => {
          console.log("This is only called once");
      });
      
      ticketManager.buy("test@email.com", 20);
      ticketManager.buy("test@email.com", 20);
      

      Save and exit, then execute this program:

      Your output will be:

      Output

      Someone bought a ticket! Someone bought a ticket! Someone bought a ticket! This is only called once Someone bought a ticket!

      The first two lines were from the first two buy() calls before the once() listener was added. Adding a new event listener does not remove previous ones, so the first event listener we added is still active and logs messages.

      Since the event listener with on() was declared before the event listener with once(), we see Someone bought a ticket! before This is only called once. These two lines are both responding to the second-to-last buy event.

      Finally, when the last call to buy() was made, the event emitter only had the first listener that was created with on(). As mentioned earlier, when an event listener created with once() receives an event, it is automatically removed.

      Now that we have added event listeners to detect our emitters, we will see how to capture data with those listeners.

      Step 3 — Capturing Event Data

      So far, you’ve set up event listeners to react to emitted events. The emitted events also pass along data. Let’s see how we can capture the data that accompanies an event.

      We’ll begin by creating some new Node.js modules: an email service and a database service. They’ll be used to simulate sending an email and saving to a database respectively. We’ll then tie them all together with our main Node.js script—index.js.

      Let’s begin by editing our email service module. Open the file in your text editor:

      Our email service consists of a class that contains one method—send(). This method expects the email that’s emitted along with buy events. Add the following code to your file:

      event-emitters/emailService.js

      class EmailService {
          send(email) {
              console.log(`Sending email to ${email}`);
          }
      }
      
      module.exports = EmailService
      

      This code creates an EmailService class that contains a send() function. In lieu of sending an actual email, it uses template literals to log a message to the console that would contain the email address of someone buying a ticket. Save and exit before moving on.

      Let’s set up the database service. Open databaseService.js with your text editor:

      The database service saves our purchase data to a database via its save() method. Add the following code to databaseService.js:

      event-emitters/databaseService.js

      class DatabaseService {
          save(email, price, timestamp) {
              console.log(`Running query: INSERT INTO orders VALUES (email, price, created) VALUES (${email}, ${price}, ${timestamp})`);
          }
      }
      
      module.exports = DatabaseService
      

      This creates a new DatabaseService class that contains a single save() method. Similar to the email service’s send() method, the save() function uses the data that accompanies a buy event, logging it to the console instead of actually inserting it into a database. This method needs the email of the purchaser, price of the ticket, and the time the ticket was purchased to function. Save and exit the file.

      We will use our last file to bring the TicketManager, EmailService, and DatabaseService together. It will set up a listener for the buy event and will call the email service’s send() function and the database service’s save() function.

      Open the index.js file in your text editor:

      The first thing to do is import the modules we are using:

      event-emitters/index.js

      const TicketManager = require("./ticketManager");
      const EmailService = require("./emailService");
      const DatabaseService = require("./databaseService");
      

      Next, let’s create objects for the classes we imported. We’ll set a low ticket supply of three for this demonstration:

      event-emitters/index.js

      const TicketManager = require("./ticketManager");
      const EmailService = require("./emailService");
      const DatabaseService = require("./databaseService");
      
      const ticketManager = new TicketManager(3);
      const emailService = new EmailService();
      const databaseService = new DatabaseService();
      

      We can now set up our listener with the instantiated objects. Whenever someone buys a ticket, we want to send them an email as well as saving the data to a database. Add the following listener to your code:

      event-emitters/index.js

      const TicketManager = require("./ticketManager");
      const EmailService = require("./emailService");
      const DatabaseService = require("./databaseService");
      
      const ticketManager = new TicketManager(3);
      const emailService = new EmailService();
      const databaseService = new DatabaseService();
      
      
      ticketManager.on("buy", (email, price, timestamp) => {
          emailService.send(email);
          databaseService.save(email, price, timestamp);
      });
      

      Like before, we add a listener with the on() method. The difference this time is that we have three arguments in our callback function. Each argument corresponds to the data that the event emits. As a reminder, this is the emitter code in the buy() function:

      event-emitters/ticketManager.js

      this.emit("buy", email, price, Date.now());
      

      In our callback, we first capture the email from the emitter, then the price, and finally the Date.now() data, which we capture as timestamp.

      When our listener detects a buy event, it will call the send() function from the emailService object as well as the save() function from databaseService. To test that this setup works, let’s make a call to the buy() function at the end of the file:

      event-emitters/index.js

      ...
      
      ticketManager.buy("test@email.com", 10);
      

      Save and exit the editor. Now let’s run this script with node and observe what comes next. In your terminal enter:

      You will see the following output:

      Output

      Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588720081832)

      The data was successfully captured and returned in our callback function. With this knowledge, you can set up listeners for a variety of emitters with different event names and data. However, there are certain nuances to handling error events with event emitters.

      Next, let’s look at how to handle error events and what standards we should follow in doing so.

      Step 4 — Handling Error Events

      If an event emitter cannot perform its action, it should emit an event to signal that the action failed. In Node.js, the standard way for an event emitter to signal failure is by emitting an error event.

      An error event must have its name set to error. It must also be accompanied by an Error object. Let’s see a practical example of emitting an error event.

      Our ticket manager decreases the supply by one every time the buy() function is called. Right now there’s nothing stopping it from selling more tickets than it has available. Let’s modify the buy() function so that if the ticket supply reaches 0 and someone wants to buy a ticket, we emit an error indicating that we’re out of stock.

      Open ticketManager.js in your text editor once more:

      Now edit the buy() function as follows:

      event-emitters/ticketManager.js

      ...
      
      buy(email, price) {
          if (this.supply > 0) {
              this.supply—;
              this.emit("buy", email, price, Date.now());
              return;
          }
      
          this.emit("error", new Error("There are no more tickets left to purchase"));
      }
      ...
      

      We’ve added an if statement that allows a ticket purchase if our supply is greater than zero. If we don’t have any other tickets, we’ll emit an error event. The error event is emitted with a new Error object that contains a description of why we’re throwing this error.

      Save and exit the file. Let’s try to throw this error in our index.js file. Right now, we only buy one ticket. We instantiated the ticketManager object with three tickets, so we should get an error if we try to buy four tickets.

      Edit index.js with your text editor:

      Now add the following lines at the end of the file so we can buy four tickets in total:

      event-emitters/index.js

      ...
      
      ticketManager.buy("test@email.com", 10);
      ticketManager.buy("test@email.com", 10);
      ticketManager.buy("test@email.com", 10);
      ticketManager.buy("test@email.com", 10);
      

      Save and exit the editor.

      Let’s execute this file to see what happens:

      Your output will be:

      Output

      Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588724932796) Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588724932812) Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588724932812) events.js:196 throw er; // Unhandled 'error' event ^ Error: There are no more tickets left to purchase at TicketManager.buy (/home/sammy/event-emitters/ticketManager.js:16:28) at Object.<anonymous> (/home/sammy/event-emitters/index.js:17:15) at Module._compile (internal/modules/cjs/loader.js:1128:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:983:32) at Function.Module._load (internal/modules/cjs/loader.js:891:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 Emitted 'error' event on TicketManager instance at: at TicketManager.buy (/home/sammy/event-emitters/ticketManager.js:16:14) at Object.<anonymous> (/home/sammy/event-emitters/index.js:17:15) [... lines matching original stack trace ...] at internal/main/run_main_module.js:17:47

      The first three buy events were processed correctly, but on the fourth buy event our program crashed. Let’s examine the beginning of the error message:

      Output

      ... events.js:196 throw er; // Unhandled 'error' event ^ Error: There are no more tickets left to purchase at TicketManager.buy (/home/sammy/event-emitters/ticketManager.js:16:28) ...

      The first two lines highlight that an error was thrown. The comment says "Unhandled 'error' event". If an event emitter emits an error and we did not attach a listener for error events, Node.js throws the error and crashes the program.

      It’s considered best practice to always listen for error events if you’re listening to an event emitter. If you do not set up a listener for errors, your entire application will crash if one is emitted. With an error listener, you can gracefully handle it.

      To follow best practices, let’s set up a listener for errors. Re-open the index.js file:

      Add a listener before we start buying tickets. Remember, a listener can only respond to events that are emitted after it was added. Insert an error listener like this:

      event-emitters/index.js

      ...
      
      ticketManager.on("error", (error) => {
          console.error(`Gracefully handling our error: ${error}`);
      });
      
      ticketManager.buy("test@email.com", 10);
      ticketManager.buy("test@email.com", 10);
      ticketManager.buy("test@email.com", 10);
      ticketManager.buy("test@email.com", 10);
      

      When we receive an error event, we will log it to the console with console.error().

      Save and leave nano. Re-run the script to see our error event handled correctly:

      This time the following output will be displayed:

      Output

      Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588726293332) Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588726293348) Sending email to test@email.com Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email.com, 10, 1588726293348) Gracefully handling our error: Error: There are no more tickets left to purchase

      From the last line, we confirm that our error event is being handled by our second listener, and the Node.js process did not crash.

      Now that we’ve covered the concepts of sending and listening to events, let’s look at some additional functionality that can be used to manage event listeners.

      Step 5 — Managing Events Listeners

      Event emitters come with some mechanisms to monitor and control how many listeners are subscribed to an event. To get an overview of how many listeners are processing an event, we can use the listenerCount() method that’s included in every object.

      The listenerCount() method accepts one argument: the event name you want the count for. Let’s see it in action in index.js.

      Open the file with nano or your text editor of choice:

      You currently call the buy() function four times. Remove those four lines. When you do, add these two new lines so that your entire index.js looks like this:

      event-emitters/index.js

      const TicketManager = require("./ticketManager");
      const EmailService = require("./emailService");
      const DatabaseService = require("./databaseService");
      
      const ticketManager = new TicketManager(3);
      const emailService = new EmailService();
      const databaseService = new DatabaseService();
      
      ticketManager.on("buy", (email, price, timestamp) => {
          emailService.send(email);
          databaseService.save(email, price, timestamp);
      });
      
      ticketManager.on("error", (error) => {
          console.error(`Gracefully handling our error: ${error}`);
      });
      
      console.log(`We have ${ticketManager.listenerCount("buy")} listener(s) for the buy event`);
      console.log(`We have ${ticketManager.listenerCount("error")} listener(s) for the error event`);
      

      We’ve removed the calls to buy() from the previous section and instead logged two lines to the console. The first log statement uses the listenerCount() function to display the number of listeners for the buy() event. The second log statement shows how many listeners we have for the error event.

      Save and exit. Now run your script with the node command:

      You’ll get this output:

      Output

      We have 1 listener(s) for the buy event We have 1 listener(s) for the error event

      We only used the on() function once for the buy event and once for the error event, so this output matches our expectations.

      Next, we’ll use the listenerCount() as we remove listeners from an event emitter. We may want to remove event listeners when the period of an event no longer applies. For example, if our ticket manager was being used for a specific concert, as the concert comes to an end you would remove the event listeners.

      In Node.js we use the off() function to remove event listeners from an event emitter. The off() method accepts two arguments: the event name and the function that’s listening to it.

      Note: Similar to the on() function, Node.js aliases the off() method with removeListener(). They both do the same thing, with the same arguments. In this tutorial, we will continue to use off().

      For the second argument of the off() function, we need a reference to the callback that’s listening to an event. Therefore, to remove an event listener, its callback must be saved to some variable or constant. As it stands, we cannot remove the current event listeners for buy or error with the off() function.

      To see off() in action, let’s add a new event listener that we will remove in subsequent calls. First, let’s define the callback in a variable so that we can reference it in off() later. Open index.js with nano:

      At the end of index.js add this:

      event-emitters/index.js

      ...
      
      const onBuy = () => {
          console.log("I will be removed soon");
      };
      

      Now add another event listener for the buy event:

      event-emitters/index.js

      ...
      
      ticketManager.on("buy", onBuy);
      

      To be sure that we successfully added that event listener, let’s print the listener count for buy and call the buy() function.

      event-emitters/index.js

      ...
      
      console.log(`We added a new event listener bringing our total count for the buy event to: ${ticketManager.listenerCount("buy")}`);
      ticketManager.buy("test@email", 20);
      

      Save and exit the file, then run the program:

      The following message will be displayed in the terminal:

      Output

      We have 1 listener(s) for the buy event We have 1 listener(s) for the error event We added a new event listener bringing our total count for the buy event to: 2 Sending email to test@email Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email, 20, 1588814306693) I will be removed soon

      From the output, we see our log statement from when we added the new event listener. We then call the buy() function, and both listeners react to it. The first listener sent the email and saved data to the database, and then our second listener printed its message I will be removed soon to the screen.

      Let’s now use the off() function to remove the second event listener. Re-open the file in nano:

      Now add the following off() call to the end of the file. You will also add a log statement to confirm the number of listeners, and make another call to buy():

      event-emitters/index.js

      ...
      
      ticketManager.off("buy", onBuy);
      
      console.log(`We now have: ${ticketManager.listenerCount("buy")} listener(s) for the buy event`);
      ticketManager.buy("test@email", 20);
      

      Note how the onBuy variable was used as the second argument of off(). Save and exit the file.

      Now run this with node:

      The previous output will remain unchanged, but this time we will find the new log line we added confirming we have one listener once more. When buy() is called again, we will only see the output of the callback used by the first listener:

      Output

      We have 1 listener(s) for the buy event We have 1 listener(s) for the error event We added a new event listener bringing our total count for the buy event to: 2 Sending email to test@email Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email, 20, 1588816352178) I will be removed soon We now have: 1 listener(s) for the buy event Sending email to test@email Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email, 20, 1588816352178)

      If we wanted to remove all events with off(), we could use the removeAllListeners() function. This function accepts one argument: the name of the event we want to remove listeners for.

      Let’s use this function at the end of the file to take off the first event listener we added for the buy event. Open the index.js file once more:

      You’ll first remove all the listeners with removeAllListeners(). You’ll then log a statement with the listener count using the listenerCount() function. To confirm it’s no longer listening, you’ll buy another ticket. When the event is emitted, nothing will react to it.

      Enter the following code at the end of the file:

      event-emitters/index.js

      ...
      
      ticketManager.removeAllListeners("buy");
      console.log(`We have ${ticketManager.listenerCount("buy")} listeners for the buy event`);
      ticketManager.buy("test@email", 20);
      console.log("The last ticket was bought");
      

      Save and exit the file.

      Now let’s execute our code with the node command:

      Our final output is:

      We have 1 listener(s) for the buy event
      We have 1 listener(s) for the error event
      We added a new event listener bringing our total count for the buy event to: 2
      Sending email to test@email
      Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email, 20, 1588817058088)
      I will be removed soon
      We now have: 1 listener(s) for the buy event
      Sending email to test@email
      Running query: INSERT INTO orders VALUES (email, price, created) VALUES (test@email, 20, 1588817058088)
      We have 0 listeners for the buy event
      The last ticket was bought
      

      After removing all listeners, we no longer send emails or save to the database for ticket purchases.

      Conclusion

      In this tutorial, you learned how to use Node.js event emitters to trigger events. You emitted events with the emit() function of an EventEmitter object, then listened to events with the on() and once() functions to execute code every time the event is triggered. You also added a listener for an error event and monitored and managed listeners with the listenerCount() function.

      With callbacks and promises, our ticket manager system would need to be integrated with the email and database service modules to get the same functionality. Since we used event emitters, the event was decoupled from the implementations. Furthermore, any module with access to the ticket manager can observe its event and react to it. If you want Node.js modules, internal or external, to observe what’s happening with your object, consider making it an event emitter for scalability.

      To learn more about events in Node.js, you can read the Node.js documentation. If you’d like to continue learning Node.js, you can return to the How To Code in Node.js series, or browse programming projects and setups on our Node topic page.



      Source link