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

Is the exchange between Ajax/jQuery and PHP a two-way street?

My jQuery ajax call looks like this: $.ajax({ type: "POST", url: ajaxurl, data: data, success: function(response){ alert(response); } }); I am retrieving data from PHP using the following code: $data_array = get_data(); forea ...

AngularJS is not immediately responsive to changes in $window.document.visibilityState

I am currently working with AngularJs version 1.4 and I need to be able to detect when a user is not on the tab of my app and when they return. To achieve this, I attempted using $watch in the following way: $rootScope.$watch(angular.bind($window, functio ...

Strategies for concealing and revealing content within dynamically loaded AJAX data

I am attempting to show and hide data that is loaded using Ajax. $.ajax({ type: "POST", url: "/swip.php", data: {pid:sldnxtpst,sldnu:sldnu}, success: function(result) { $('.swip').prepend(result); } }); This data gets ...

Issue with Chart.js V3.20: Struggling to Filter Legend Labels

Building a dynamic line chart using Chart.js with the capability of up to 19 datasets. The issue arises when there are less than 19 datasets, as the legend still displays for these unused datasets. Previously, a function was used in Chart.js 2.6.0 options ...

Executing two distinct SQL queries within one nodejs function

I'm facing an issue with updating two tables in my database - the stockmaster table and the prodstock table. I've been trying to run a query using a function to update both tables simultaneously, but unfortunately, it's not working as expect ...

Toggle the hamburger menu using JavaScript

How can I close my hamburger menu when clicking a link for one page navigation? The menu is functioning properly, but I need a way to close it. Unfortunately, I have limited knowledge of JS. I only have the HTML and CSS for this: HTML in index.html file ...

Organizing Parsed JSON Data with JavaScript: Using the _.each function for Sorting

var Scriptures = JSON.parse( fs.readFileSync(scriptures.json, 'utf8') ); _.each(Scriptures, function (s, Scripture) { return Scripture; }); This code extracts and displays the names of each book from a collection of scriptures (e.g., Genesis, ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

The button attached to the jQuery .toggle() function requires two clicks to activate

My objective is twofold: To dynamically load the Disqus script embed.js only when the "Show Comments" button is clicked. To toggle the visibility of the disqus_thread div using the same button while also changing the button's text. The issue I am f ...

The Element Datepicker incorrectly displays "yesterday" as an active option instead of disabled when the timezone is set to +14

After adjusting my timezone to +14 using a chrome plugin, I noticed that the calendar app is displaying incorrect disabled dates. You can view the issue here. This is the formula I'm currently utilizing to disable dates: disabledDate(time) { re ...

Converting PHP arrays into JavaScript arrays with the help of json_encode()

Is there a way to pass an array from PHP to the JavaScript function console.log()? I'm currently simulating a database and need help with this specific task. Despite not having an array declared in my code, I attempted to use the .getJSON() function w ...

Automatically preselect the checkbox inputs with the API and update their status when they are interacted with

Hello fellow developer, I trust you are doing well. I am looking to have the checkboxes automatically checked based on data from the API and update their status when interacted with. I've tried different approaches but haven't found the right sol ...

When implementing Firebase Cloud Messaging with React, the token generated by firebase.messaging().getToken() will vary with every refresh

I'm working on a React web app using Gatsby and I want to integrate push notifications through FCM. My firebase-messaging-sw.js service worker is set up, and I'm trying to retrieve a token using the following method in my app: messaging .req ...

Monitor changes in the select tag to display the updated value and output

I am new to using jQuery. While I have practiced using native PHP Ajax in the past, I now recognize the need to learn jQuery due to current technological advancements and demands. When the select tag changes, I send the "types" value via POST method to a ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

Eliminating unnecessary CSS from the codebase of a website

Currently, I am making adjustments to a website template that I downloaded for free online. I have noticed that even if I delete a div from the code, the corresponding CSS styles remain in one or more files. Is there any tool available that can automatic ...

Troubleshooting problem with Angular Materials' md-datepicker not displaying correctly in wide browser windows

While using the md-datepicker component in my application, I noticed that it does not display properly on larger browser widths. It only seems to work as expected on small and x-small viewports. Please refer to the attached screenshot for reference. This ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...

What is the best way to retrieve specific items using the Chosen JQuery plugin?

I have a multiple select box set up with chosen, but I am unsure how to retrieve the selected items. <select class="multiselect" multiple="" name="parlementId"> @foreach (Politicus p in politici) { <optio ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...