ES6 promises: the art of connecting functions with parameters

Looking for a way to chain functions with delays? Here is an example of what I have tried:

Promise.resolve()
.then(setKeyframe('keyframe-0'))
.then(delay(3000))
.then(setKeyframe('keyframe-1'))
.then(delay(3000))
.then(setKeyframe('keyframe-2'))
;

function delay(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms);
  });
}

function setKeyframe (name) {
  var elem = document.getElementsByClassName('animation-container')[0];
  elem.className = 'animation-container ' + name;
}

However, all the functions appear to be executed one after the other without any delay. The delay function does not seem to work as expected in this chaining process. What could be the issue here?

Answer №1

Your error may be more obvious with a function that has no arguments:

The correct method:

Promise.resolve().then(setFirstKeyframe)

In the above code, the function setFirstKeyframe is passed as an argument to .then, for the promise to execute later.

The incorrect method:

Promise.resolve().then(setFirstKeyframe())

In this case, setFirstKeyframe is executed immediately (!), and its result (a promise) is then passed to then (which is ignored since then expects a function).

For functions with arguments, use an anonymous function:

Promise.resolve().then(function() {
  return setFirstKeyframe('keyframe-0');
})

This is where es6 arrow functions shine:

Promise.resolve().then(() => setFirstKeyframe('keyframe-0'))

Answer №2

.then() takes in a function as input, which has the potential to return a promise

However, in this case, you are supplying a promise directly

// Correct
Promise.resolve().then(() => { return new Promise(); });

// Incorrect
Promise.resolve().then(new Promise());

Answer №3

One common mistake is calling functions instead of passing them as handlers.

Promise.resolve('keyframe-0')
.then(setKeyframe)
.then(delay(3000, 'keyframe-1'))
.then(setKeyframe)
.then(delay(3000, 'keyframe-2'))
.then(setKeyframe)
;

function delay(ms, value) {
  return function (val) {
    return new Promise((resolve, reject) => {
      setTimeout(resolve, ms, value !== undefined ? value : val);
    });
  };
}

function setKeyframe(name) {
  var element = document.body;
  element.className = 'animation-container ' + name;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.keyframe-0 { background: red; }
.keyframe-1 { background: green; }
.keyframe-2 { background: blue; }

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

The hyperlink in the HTML code is malfunctioning

While working on a Wix website, I encountered an issue with the code snippet below: // JavaScript var countries = [ { name: 'Thailand', link: 'www.google.com' }, { name: 'Tanzania', link: '' }, { name: &ap ...

Navigate to a fresh HTML page upon form submission

I'm completely new to the world of web apps and JavaScript, and I'm facing an issue where my form submission doesn't redirect me to a thank you page. Instead, it just leads to a blank page every time. I've tried researching solutions on ...

transmit data via Javascript to interact with a Python web application

I'm having issues sending a json object from JavaScript to a Python webservice. The service keeps treating it as a string. Here are the codes for both client and server sides: CLIENT SIDE: $("#button").click(function () { $.ajax({ ...

Attempting to manipulate information within the @click event handler embedded within a v-for loop

I am using a v-for loop to select dialog boxes that I want to open. <v-card @click="page.model = true"> In this code, page.model is being used as the v-model for a v-dialog component. data() { return { dialog1: false, dia ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

Counting Slides in a Slick Carousel

I am currently working with the slick carousel in React.js using ES6 and I'm having trouble getting the slide count. In my function, I can successfully retrieve the count inside the event listener but outside it returns null. Can someone point out wha ...

Using jQuery to loop through a table and retrieve the button value from every row

I have a challenge with dynamically created buttons in a table. My goal is to loop through the table, identify the rows that have a checked checkbox, and retrieve the value of a button within that row. I then need to store these values in an array. Unfortu ...

How can I identify the appropriate default option element in AngularJS?

Query: I have a scenario where I need to set the default option in an angular dropdown menu based on values from an array of Person objects. How can I achieve this when initially loading the UI? http://plnkr.co/edit/hvIimscowGvO6Hje35RB?p=preview <!DO ...

Creating a responsive design for mobile apps in Ionic using CSS

I need help with making my Ionic app responsive across all mobile devices. The design on the page was created using CSS, but it is not displaying properly on every device. How can I ensure that it adapts to different screen sizes? <template> <Io ...

deployJava.js injects a new <embed> element into the header section of the webpage

I've ran into an issue with the Java applets on my website. I included the deployJava.js load tag in the head section of the page, but when I look at the resulting HTML in Chrome debugger, this script seems to be breaking my head content and starting ...

Is it possible to achieve a height transition using CSS instead of relying on JavaScript

I created these custom cards using a combination of HTML, CSS, and JavaScript. However, I've noticed that the height transition animation is not as smooth as I'd like it to be, especially on certain pages. Is there a way to achieve this animation ...

A CSS rule to display a nested list on the left-hand side

I created a menu that you can view here. When hovering over "tanfa demo example," the sublist appears on the right side. The issue I'm facing is that my menu is positioned all the way to the right, which means the sublist also appears on the extreme ...

What method would you recommend for modifying HTML text that has already been loaded using JSP?

Is there a way to update text on an HTML document without reloading the entire page? I'm looking to create a simple "cart" functionality with 5 links on a page. When a link is clicked, I want it to increment the "items in cart" counter displayed on th ...

Utilizing Angularjs for dynamic data binding in HTML attributes and style declarations

Can someone help me figure out how to use an AngularJS model as the value for an HTML attribute? For example: <div ng-controller="deviceWidth" width={{width}}> </div> Additionally, how can I achieve this within <style> markup? Where ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Tips for Preserving the HTML Page State After Making jQuery Changes

Hi there! I am currently working on developing a card game using HTML5, CSS3, and Javascript. This game will communicate with a server built on node.js, facilitated by socket.io for data transmission. One of the key features I am trying to implement is th ...

`How can I retrieve a PHP variable using a JavaScript AJAX request?`

When sending an AJAX request, I encounter a situation where: //javascript var rq = new XMLHTTPrequest(); rq.open('POST','test.php', true); rq.send(JSONString); Within "test.php" file, the following action is taken: //php $data = "Hel ...

Nested pages are causing jQuery plugins to malfunction

I am currently working on a website, but I am facing some issues with the product listing pages and the tips and tricks page. It appears that there is an issue with jMenu and jFlipBook plugins not functioning properly. Since I didn't develop the origi ...

Is there a way to automatically display the detailsPanel in Material-table upon loading?

I am currently working on creating a subtable for the main React Material-Table. So far, everything is functioning correctly as expected, with the details panel (subtable) appearing when the toggle icon is pressed. Is there a way to have it displayed by d ...

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...