completed() versus finished()

As I was going through the documentation for passport, I came across an interesting observation regarding the use of serialize() and deserialize(). It seems that done() is called without being explicitly returned in one scenario.

However, while setting up a new strategy using passport.use(), the callback function uses return done(). This made me question whether this is a crucial aspect to grasp or simply a convention followed from the documentation.

If you want to explore this further, you can visit the official documentation at .

Here is a snippet from the docs for your reference:

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

Answer №1

Using return done() will halt the execution of the function immediately. Subsequently, any code lines following that particular line within the function will be disregarded and not processed.

On the other hand, if done() is not preceded by return
, the function will continue its execution. This implies that any code lines after that specific line within the function will be executed.

An example that demonstrates this behavior is within the snippet for passport.use() found in the Passport documentation. In this scenario, there is code present after the initial three return done() statements. It is crucial for the function to terminate immediately upon the first invocation of done() to prevent the execution of subsequent instructions:

passport.use(new BasicStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      if (err) { return done(err); } 
      if (!user) { return done(null, false); }
      if (!user.validPassword(password)) { return done(null, false); }
      // The following line is the success case. We do not want to execute it
      // if there was an error, a falsy user or a user without a valid 
      // password. If we removed the return keywords from the previous lines
      // of code, the success case would be triggered every time this
      // function was called
      return done(null, user);
    });
  }
));

To illustrate the distinction between done() and return done(), two executable snippets have been included. Despite their similarities, the behavior differs significantly:

done() without return:

const done = console.log

const assessThreatLevel = threatLevel => {
  if (threatLevel === 'all good') done('relax :)')
  done('launch the missiles!')
}

assessThreatLevel('all good')

return done():</p>

<p><div>
<div>
<pre class="lang-js"><code>const done = console.log

const assessThreatLevel = threatLevel => {
  if (threatLevel === 'all good') return done('relax :)')
  done('launch the missiles!')
}

assessThreatLevel('all good')

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

Image displaying recreation of drop down lists similar to those found on Facebook pop-up windows

Seeking guidance on how to create popup drop-down lists similar to Facebook's "Who liked this link?" feature. I believe it involves the use of jQuery. Click here for an example image. Any suggestions, folks? ...

Issue with AngularJs: $http post only posting single item to collection inside a for loop

I have a collection that requires me to post multiple items in a for loop. Below is the code snippet: for(i = 0; i < 28; i++) { var request = $http({ method: "post", url: "/students", ...

Creating a unique WooCommerce product category dropdown shortcode for your website

I am having trouble implementing a WooCommerce categories dropdown shortcode. Although I can see the drop-down menu, selecting a category does not seem to trigger any action. Shortcode: [product_categories_dropdown orderby="title" count="0" hierarchical=" ...

Exploring functional elements in Express and EJS

Within many MVC frameworks, there is often a feature that allows for actions to be invoked from the view. For ASP.NET MVC, this functionality is referred to as RenderAction, while other frameworks may call it SubActions, Viewlets, etc. In my EJS layout fi ...

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

"An issue with AngularJS ngTable causing a delay in the rendering of Ajax

Struggling with ngTable Setup Having trouble mastering the use of ngTable by going through the ngTable ajax demo. I attempted to follow along with the example as closely as possible, but I'm encountering a deviation in defining an ngResource inline w ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

Show a button using CSS when the cursor is hovering

Expressing my gratitude to everyone! I need assistance with implementing a function in reactJS where the <button /> remains hidden during page loading and reveals itself when hovered over. Despite trying various methods, I have been unable to resolve ...

Utilizing component data in Vue.js to configure the router-link attribute

Is there a way to pass component data in <router-link to="...">? Here's an example: var data = { files: [{ name: "test", path: "/test" }] }; var component = { data: function() { return data; ...

Problem with finding Rails controller file in .coffee extension

I recently started learning Rails and came across a file called welcome.js.coffee in the assets javascripts directory. # Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in applica ...

Express.js is stuck in a continuous loading loop due to an error occurring within the generator

I have observed that when there is an error within a generator, express.js continues processing without halting, making it difficult to identify the specific error. My query is: how can I stop express.js and display the error message whenever there is an e ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Encountering an unhandled promise rejection issue with Knex's batchInsert function when attempting to insert arrays larger than 3 elements

I am currently working on an express app and utilizing Knex as the query string builder. During batch insert operations with an array of 1000+ objects, I encountered an error when the array exceeded a certain length. The specific error message is provided ...

A collection of collections

Alright, listen up. I've got a JSON file with an array inside another array. Here's a snippet of the JSON file: { "keys": [ { "game": "Counter-Strike: Global Offensive", "price": "5", "listofkeys" ...

What measures can I implement to prevent two users from simultaneously adding the same product ID to their shopping carts?

My goal is to update the router functionality so that only one user can choose the product Id of a particular product at any given time. router.get('/add-to-cart/:id', function(req, res, next) { var productId = req.params.id; var cart = new Cart ...

Having trouble selecting the clicked element after a successful Ajax call, especially when there are multiple elements with the same name

When dealing with multiple elements that share the same class name, I am attempting to target the 'clicked' element upon a successful Ajax return. <td data-name='tom' class="status"><a href="">click< ...

The responses for several HTTP POST requests are not being received as expected

I am facing a challenge in retrieving a large number of HTTP POST requests' responses from the Database. When I try to fetch hundreds or even thousands of responses, I encounter issues with missing responses. However, when I test this process with onl ...

Improving Performance in AngularJS Through Efficient Scope Passing Between Controllers

I am facing a situation in my AngularJS project where I have two controllers - controller 1 is constantly present in the view, while controller 2's visibility can change based on the view. In order to ensure that controller 1 has access to certain sco ...

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...