The reason behind the successful execution of the final .then in promise chaining

I am new to JavaScript and have encountered an interesting problem with the following code. Even though I haven't returned anything from the .then method, the last .then (blue color) works instead of the first one (red color). Can someone explain why this is happening?

let bodyBgChange = (color, delay) => {
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            document.body.style.backgroundColor = color
            resolve()
        }, delay)
        
    })
}

bodyBgChange('green',1000)
    .then(()=>{ 
        bodyBgChange('red', 1000)
    })
    .then(()=>{
        bodyBgChange('yellow', 1000)
    })
    .then(()=>{
        bodyBgChange('pink', 1000)
    })
    .then(()=>{
        bodyBgChange('blue', 1000)
    })
    

Answer ā„–1

It is important not to forget the return statement or to utilize the arrow function's implicit return

let changeBackground = (color, delay) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      document.body.style.backgroundColor = color
      resolve()
    }, delay)

  })
}

changeBackground('green', 1000)
  .then(() => {
    return changeBackground('red', 1000)
  })
  .then(() => {
    return changeBackground('yellow', 1000)
  })
  .then(() => {
    return changeBackground('pink', 1000)
  })
  .then(() => {
    return changeBackground('blue', 1000)
  })

Answer ā„–3

There might be a misunderstanding with the usage of then in this context.

Even if each of your then hooks are executed, it may appear that only the last one is "working" due to them all having the same timer set. By returning values within your then hook, you can pass on that value to the next then hook and achieve the expected behavior in this scenario.

let changeBackgroundColor = (color, delay) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      document.body.style.backgroundColor = color
      resolve()
    }, delay)
  })
}

changeBackgroundColor('green', 1000)
  .then(() => {
    return changeBackgroundColor('red', 1000)
  })
  .then(() => {
    return changeBackgroundColor('yellow', 1000)
  })
  .then(() => {
    return changeBackgroundColor('pink', 1000)
  })
  .then(() => {
    return 'foo'
  })
  .then((val) => {
    // val === 'foo'
  }

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

Tips for shifting a designated row upward in Chrome using JavaScript

Currently, I am working on a Javascript function that moves up a selected row. However, the issue I am facing is that when the row moves up, the old row is not being removed. For instance, if I move up the 'bbbb' row, it successfully moves up bu ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

JavaScript prototypal inheritance concept

During my free time, I like to dabble in JavaScript, but Iā€™m currently struggling with this particular topic. var person = new Person("Bob", "Smith", 52); var teacher = new Teacher("Adam", "Greff", 209); function Humans(firstName, lastName) { this. ...

The default value of components in Next.js

I'm working on establishing a global variable that all components are initially rendered with and setting the default value, but I'm unsure about how to accomplish the second part. Currently, this is what I have in my _app.tsx: import { AppProps ...

Enhance the table using Django URL tag along with JQuery

I am currently working on a table that is being populated with user details and I would like to include a Django URL tag within the row, extracting the primary key in the process. Here is an example of what I am trying to achieve: function putTableData(re ...

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

Enclose every line of the paragraph within a <span> element

My <div> element is configured to display a paragraph without any line breaks, similar to the example below: <div> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dum ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

Comment sections that refresh automatically after being posted

I am determined to provide a clear explanation. Despite having some code, I am uncertain about how to make it clone comments and add new ones with user inputted text. Below is the snippet of code I am struggling with: <!DOCTYPE html> <!-- this i ...

Arrange the div and ensure that the external JavaScript file functions properly when the page loads

I am encountering an issue with my JavaScript and CSS code. It works perfectly fine within the fiddle environment but fails to function properly outside of it. Here is the link to the fiddle When I embed the code into an HTML document directly, it does n ...

Ways to restrict a function to a single DOM element using either its id or class

This script is responsible for dynamically loading pages on my website. It works fine, except that it currently iterates over all anchor tags a on the site, whereas I want it to iterate only through my navigation menu. Here is the navigation menu: <div ...

What makes using setInterval with a self-invoking function a smarter choice?

I recently came across an explanation on how to properly use the setInterval() function. Essentially, it was mentioned that (function(){ // perform some actions setTimeout(arguments.callee, 60000); })(); ensures that the subsequent call from setTim ...

What sets npm run apart from npm start?

Our repository contains a substantial amount of TypeScript code that we can compile and execute using "npm run dev." This setup enables us to access the test JavaScript code via localhost. However, when examining the code in the Chrome debugger, approxim ...

Get the color at a specific index in a JavaScript array

When I click a button, a pie chart is generated using chartjs. The results are displayed based on the filters applied, showing (Name | Value%): Service_1 | 10 Service_2 | 15 Service_3 | 75 Sometimes, certain results may not appear: Service_1 | 20 S ...

Error Message: Namespace Invalid in Node.js Application Utilizing Mongoose Library with MongoDB Atlas Database

I've been working on a Node.js application similar to Twitter, utilizing Mongoose (version 8.0.2) to communicate with a MongoDB Atlas database. However, I'm stuck dealing with an error message that reads MongoServerError: Invalid namespace specif ...

Tips for ensuring a successful POST request using a hyperlink tag

Within my view file, I have the following code snippet: <a href="/logout" role="button" class="btn btn-lg btn-primary left-button">Logout</a> Inside my app.js file, I have implemented the following route for loggi ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

The hyperlink functionality is disabled because Javascript is set to return false

JS Fiddle Example When using the 'FOO' and 'BOO' items in the navigation bar to open dropdown boxes, I have implemented a code that closes them when a click event occurs outside. This code has been working fine as shown below: $(docum ...