Navigating through the execution of a program with the use of

As I navigate my way through learning express, a question has arisen regarding the mechanics of the next() function.

  1. Is my understanding correct that when next() is invoked, it immediately initiates the execution of app.get, while anything below next() is carried out asynchronously?
  2. If this is indeed the case, why is the message 'Am I executed?' not displayed in the console when there is a significant delay set within the setTimeout() function?

I would appreciate a detailed explanation of the execution flow within the code provided below.

app.param('seriesId', (req, res, next) => {
  ... // Verify the presence of the series
  console.log('I am executed');
  next();
  setTimeout(() => {console.log('Am I executed?')}, 1000); // Displays after 100ms, does not display after 1000ms
});

app.get('/:seriesId', (req, res, next) => {
  ... // Query the database to retrieve the series object
  res.status(200).json({series: series});
});

Answer №1

When you call next(), control is passed to the next middleware in the pipeline. In this scenario, that would be the app.get in your example.

It's important to note that this method doesn't act like a typical return statement. Any code following the next() call will still be executed.

For instance, if you were to start the server and visit http://localhost:1337/foo, the log statements would appear as follows:

  1. well here we are
  2. executing the get
const express = require('express');

const app = express();

app.param('param',(req, res, next) => {
    next();
    setTimeout(() => console.log('well here we are'), 1000);
});

app.get('/:param', (req, res) => {
    setTimeout(() => {
        console.log('executing the get');
        res.status(200).send();
    }, 2000);
});

app.listen(1337);
console.log('app started at http://localhost:1337');

Ensuring Clarity in Middleware Logic

To prevent confusion, it's best practice to place calls to next() at the end of your execution. For example, avoid this:

if(aCondition) {
    next();
}
next(new Error('Condition was false'));

Instead, consider doing this:

if(aCondition) {
    next();
} else {
    next(new Error('Condition was false'));
}

Alternatively, you can always return next() calls to prevent further execution of middleware code.

Handling Asynchronous Operations in Middleware

Finally, if you need to run asynchronous code in your middleware, ensure you only call next() once this code has completed execution.

For example, avoid doing this:

loadUserFromDB()
    .then(u => req.user = u);
next();

Instead, consider the following approach:

loadUserFromDB()
    .then(u => {
         req.user = u;
         next();
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

Testing XMLHttpRequest with Jasmine: A Complete Guide

Is there a way to test the onreadystatechange function on XMLHttpRequest or pure JavaScript AJAX without using jQuery? I need to do this because I'm working on a Firefox extension. It seems like I may have to use spies, but I'm having trouble bec ...

Change classes of sibling elements using Angular 2

Imagine you have the following code snippet: <div id="parent"> <div class="child"> <div class="child"> <div class="child"> </div> I am looking to automatically assign the class active to the first child element. ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

Error-free saving issue with Mongoose model in Node.js

While developing a simple Node.js Express API, I encountered an unusual issue. I created a model, inserted data into it, and attempted to save it to my MongoDB database. However, the record was not saved, and no errors were reported. I thoroughly checked f ...

There were no visible outputs displayed within the table's tbody section

import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = [{"id":1,"isActive":true,"object":"Communication","previ ...

Comprehending the intricacies of routing within AngularJS

Question: I've been looking into this issue, but there seems to be conflicting answers. I created a simple example in Plunker to understand how routers work in AngularJS, but I'm having trouble getting it to function properly... Below is my inde ...

Duplicate a DOM element and incorporate animation into it

After extensively researching articles and documentation on this topic, I have yet to find a solution that aligns with the approach I am attempting to implement. My scenario involves an array of category items which contain a nested array of products be ...

Getting JSON key and value using ajax is a simple process that involves sending a request

There is a JSON data structure: [{"name":"dhamar","address":"malang"}] I want to know how to extract the key and value pairs from this JSON using AJAX. I attempted the following code: <script type="text/javascript> $(document).ready(function(){ $ ...

The Apollo Client mutation input type is missing data

Currently, I am working with Apollo-client and facing an issue while making a mutation on the client. It seems that when I perform my mutation, the data being passed to the server becomes void. Below is my mutation type: type: recipeType, args:{ ...

Error code -4058 ENOENT indicates that the file or directory does not exist. This issue is usually caused when npm is unable to locate a specific file

Trying to start a react project on my D: drive while having node installed on the C: drive resulted in an error: D:\react> npm start npm ERR! code ENOENT npm ERR! syscall open npm ERR! path D:\react/package.json npm ERR! errno -4058 npm ERR! ...

Is there a way to transfer non-string parameters from JavaScript to a Java .jar file?

In my AngularJS application, I want to call a .jar file to handle the uploading of images/files. The idea is for Angular to send blob data (image information) to the .jar, along with the folder name where the image should be stored. My Java method would r ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

Is it more suitable for a library used by getStaticProps to be classified as a normal dependency or a dev

When working with NextJS's getStaticProps, I am implementing a library that is only utilized during build time. Should this library be categorized as a regular or development dependency in my package.json? ...

Incorporate pictures from the popup onto the main page

I have developed a basic PHP image editor script where users can select images from galleries and merge them together. However, I am facing an issue: The galleries open in a popup while the editor area is on the parent page. I am looking for a JavaScript ...

Ways to change the color of a button when it is clicked?

I am attempting to change the color of a button on another button click, but it doesn't seem to be working. function show_col(){ console.log("hello"); var path=localStorage.getItem(".physics_section #color1 button"); $(''+ ...

The Bootstrap tab feature is malfunctioning when a tab is using data-target instead of href

While developing bootstrap tabs for an Angular app, I decided to use the data-target attribute instead of the href attribute to avoid any interference with routes. Here's a snippet of how I structured the tabs: <ul class="nav nav-tabs" id="myTab"& ...

Converting dynamic text enclosed in asterisks (*) into a hyperlink on a webpage with the use of JavaScript

I'm facing a unique situation where I need to transform specific text on an HTML page into anchor tags using JavaScript/jQuery. The text format is as follows: *www.google.co.uk/Google* *www.stackoverflow.com/StackOverflow* The desired outcome should ...

Is there a way to securely embed YouTube videos in my web application without exposing the direct video links?

I'm hoping to integrate YouTube videos into my web application, but I need a way to prevent users from accessing the direct video links while they are using the app. Does anyone have any suggestions on how this can be accomplished? I am unsure of how ...

Is there a way to merge these arrays into a single array?

With the current code I am obtaining numerous JSON objects within separate arrays: Here is the code snippet: for (let i=1; i<=150;i++){ fetch(`A valid URL ${i}`) .then(result => result.json()) .then(result => console.log(result.data.results)) ...