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

How to implement dynamic aggregate functions with parameters in Express and Mongoose

I have implemented an aggregate function in mongoose to fetch some data, with a static implementation. app.get("/male",function (req,res) { Record.aggregate([ { $match: {"gender": "male"} }, { $group:{ _i ...

Incorporating an NPM module into a React file: Webpack encounters resolution issues

After reviewing information from this source and here, the process of publishing a react module to NPM and then using it in another project while having the component in the node_modules directory should be as follows: Create and export a module Specify ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Ways to extract the ID by iterating through buttons

I encountered a message in my browser while looping through buttons with onclick function(). Are there any alternative solutions? Error handling response: TypeError: self.processResponse is not a function at chrome-extension://cmkdbmfndkfgebldhnkbfhlneefd ...

I am puzzled as to why the JSON response is visible in the browser but cannot be forwarded to the Ajax callback function, causing the page to remain on the initial request page

Currently, I am in the process of developing a web application that utilizes AJAX and servlet. My main focus right now is creating a functional login page for the application. Although the servlet successfully generates a response in JSON format, the issu ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Blocking the space bar in JavaScript is a useful technique that can be

I'm in the process of developing an application and I'm looking to prevent the space bar from scrolling my page My framework of choice is VUE, and I am trying to trigger a method using an event handler However, when I attempt to call the ' ...

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

Configuring Axios header in Java backend based on the value stored in the express session

I am currently working on a frontend app using node.js express for server-side rendering. This app calls java backend endpoints and I use Axios to make the requests. A specific header named "agent-id" needs to be set in every request that is sent from expr ...

Changing VueJS duplicate values with v-model (:value, @input)

I'm encountering an issue with v-model in my custom component. I prefer not to use State or Bus. Currently, the component successfully returns a single value in App.js, but it duplicates itself. I'm struggling to resolve this problem, so any help ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

Using the novalidate attribute in Angular 4.0.0

Since migrating to angular 4, I have encountered a peculiar issue with my template-driven form. The required attribute on the input field appears to be malfunctioning. It seems like the form has the novalidate attribute by default, preventing HTML5 validat ...

Store Dark Mode preferences in the browser's local storage using React and Material-UI

Is there a way to save the dark mode setting in localStorage? Can this approach be used for storing it? Any suggestions on how to achieve this would be appreciated. Thanks, cheers! function App() { const [darkState, setDarkState] = useState("&qu ...

How can I utilize jQuery to save a simple text string in a mySQL database?

Seeking guidance on this jQuery code snippet: $('.bggallery_images').click(function () { var newBG = "url('" + $(this).attr('src'); var fullpath = $(this).attr('src'); var filename = fullpath.replace('im ...

Arranging a JSON Object Array in JavaScript by its alphanumeric key attribute order

I need assistance sorting this JSON array by unitId var array = [ { id: 10, unitId: 'unit17' }, { id: 11, unitId: 'unit19' }, { id: 13, unitId: 'unit27' }, { id: 12, unitId: 'unit2' }, { id: 13, unitId: 'unit ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

Maximizing the power of Webpack alongside Google Maps API

I have been using Webpack along with the html-webpack-plugin to compile all my static files. However, I am facing an issue when integrating it with the Google Maps API. Here is the code snippet: var map; function initMap() { map = new google.maps.Map(d ...