The effectiveness of a promise chain is consistent, even when the return statement is subject to conditions

After reorganizing this sequence, I am perplexed at how it continues to function regardless of a conditional return statement in one of the .then sections:

function addList(name) {
let listObj = {};
listObj.name = name;
return nameExists(name) //returns a promise<boolean>
    .then((result) => {
        console.log("foo");
        return result; //even without this return statement, the chain would not work as expected
                       //since it does not deliver a 
                       //promise otherwise.
    })
    .then(bool => {
        listObj.unique = !bool;
        if (validListID(name)) { //this is a synchronous regex function
            listObj.unique = false;
        }
        if (!listObj.unique)
            return Counters.getNewShortListId(); // returns Promise
        //The next chain still gets executed even when the condition isn't met,
        //which is intriguing given that no promise is returned.
    })
    .then((id) => { //even if listObj.unique = true, this section runs smoothly,
                    //and it functions flawlessly, but why?
        listObj.__id = id;
        return new List(listObj).save();
    });
}

The behavior of this code has left me puzzled. Isn't the promise chain supposed to break without a return promise?

Answer №1

When a Promise is not returned from a .then, the next .then will still function properly without any errors being thrown. However, the parameter for its callback will consistently be undefined:

Promise.resolve()
  .then(() => {
    // no return value
  })
  .then((param) => {
    console.log(param);
  });

If you are confident that the resolution of getNewShortListId always results in a non-undefined value, simply verify that the following .then's id is not undefined.

.then((id) => {
    if (id !== undefined) {
        listObj.__id = id;
        return new List(listObj).save();
    }
});

Alternatively, you can have the preceding .then create the Promise instead of the subsequent .then:

if (!listObj.unique)
  return Counters.getNewShortListId()
    .then((id) => {
      listObj.__id = id;
      return new List(listObj).save();
    })

If you find the appearance of nested .thens unattractive, you may convert the nested .then callback into a pre-defined named function (e.g., const processId = (id) => ...).

You also have the option to throw an error (e.g.,

if (listObj.unique) throw new Error()
) to effectively exit the current .then chain and transition directly to the subsequent .catch, bypassing any intermediate .thens - although it is generally advised not to use errors for controlling program flow.

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

Node/Express: The $ symbol is failing to recognize the input for PORT 8080

What steps should I follow to run my PORT on 8080? Is it necessary to install any dependencies? const app = require('express')(); const PORT = 8080; app.listen( PORT, () => console.log('It's now running on http://localhost:$ ...

Can data sent to php via ajax be manipulated?

To restrict the number of characters a user can input in a textarea, I have implemented a character counter. // part of tinymce setup: function (ed) { ed.on('keyup', function (e) { var maxchars = <?php echo $max_chars_allowed; ?>; ...

What causes an error when attempting to add a new user to the database?

Currently, I am delving into the world of Mongodb. To kick things off, I initiated by executing npm install --save mongoose uuid within the confines of Terminal. The primary objective of my project revolves around storing user information in the database. ...

showing console logs before initializing preferences may lead to inaccurate results

My Content Management System (CMS) is WordPress. Recently, after making some changes, I encountered an error on a specific page: An error occurred: loading pref showConsoleLogs before prefs were initialised, leading to incorrect results being displayed - ...

Apache conf file configured with CSP not functioning properly when serving PHP files

While configuring the Apache CSP lockdown for a site, I encountered an unusual behavior when opening the same file as a PHP script compared to opening it as an HTML file. The HTML file looks like this: <html> <head> <meta http-equiv= ...

Troubleshooting "Nodejs Socket hang up & ECONNRESET" when sending an HTTP post request from a Meteor app to a Node.js

Utilizing a node server for managing all push notification services like GCM and APN. I have 2 separate servers in operation - one hosting Meteor and the other running Node.JS to handle push notifications. (Both servers are distinct) The primary applicat ...

To properly render an HTML file before loading a JavaScript file, express.static fails to serve the HTML file

Within my server.js file, the following code is present: var path = require('path'); var express = require('express'); var app = express(); var htmlRoutes = require('./app/routing/routes.js')(app, path, express); As for my r ...

Trouble triggering hidden radio button in Angular 9 when clicked

I have implemented radio buttons within a div with the following CSS styles (to enable selection by clicking on the div): .plans-list { display: flex; justify-content: center; margin: 2rem 0; .plan { display: flex; margin: 0 0.5rem; p ...

SPRING --- Tips for sending an array of objects to a controller in Java framework

Can someone help me with this issue? I am using AngularJS to submit data to my Spring controller: @RequestParam(value = "hashtag[]") hashtag[] o The above code works for array parameters but not for an array object. This is my JavaScript script: $http ...

Encountering an error in Angular Chosen where the forEach function is not recognized

Implementing Angular Chosen for a multi-select dropdown menu to choose nationalities. https://github.com/localytics/angular-chosen An error message is popping up saying: "a.forEach is not a function" This error seems to occur regardless of whether one, ...

What could be causing my for loop to become unresponsive?

My for loop seems to be populating all fields with the last object parsed. http://codepen.io/anon/pen/EKxNaN This is my current code. I created something similar on CodePen since I can't access JSON from the original source there. var championMaste ...

limiting the number of HTTP requests within a JavaScript forEach loop

In my current coding situation, I am facing an issue where the HTTP requests are being made simultaneously within a forEach loop. This leads to all the requests firing off at once. const main = async () => { items.forEach(async (i: Item) => ...

Initiate and terminate server using supertest

I've developed a server class that looks like this: import express, { Request, Response } from 'express'; export default class Server { server: any; exp: any; constructor() { this.exp = express(); this.exp.get('/' ...

Leveraging periods within a MySQL database: Node.js for seamless updates

I am currently facing a challenge in updating a column name that contains a period in node using node-mysql. I appreciate the convenience of being able to update multiple columns by providing an object with keys, but the string escaping process with node-m ...

What could be causing my web application to not properly identify angular.js?

As a newcomer to angular, I have been struggling to incorporate it into my web application (VS) as I keep encountering issues with recognizing angular. Despite trying various methods, the result remains the same - angular is not being recognized. I dow ...

The intricate scripting nestled within the jQuery function

When using jQuery, I am looking to include more codes within the .html() function. However, I also want to incorporate PHP codes, which can make the writing style quite complex and difficult to read. Is it possible to load an external PHP/HTML script? fu ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

Removing the dollar sign and retaining only the numerical values in an array using JavaScript

Using the code snippet below, I am attempting to retrieve elements by their class name in JavaScript and save them in an array. This is the current output I receive: "I received this output from the initial prices array $30.00, $20.00, $40.00" My inquiry ...

How to choose multiple images in Ionic framework

I am working with the following HTML structure: <div ng-repeat="image in images"> <img ng-src="img/{{image}}_off.png" /> </div> Additionally, I have the following JavaScript code in the controller: $scope.images = ['imga',&ap ...

Executing Parent function in Reactjs (Triggering Drawer when menu item is clicked using Material-ui)

I'm having some trouble trying to activate the drawer when a user clicks on a menu item. Unfortunately, my current solution is not working as expected. Can anyone provide assistance? Parent import React, { Component } from 'react'; // Impo ...