Attempting to grasp the concept of ES6 Promises by running three setIntervals consecutively

To gain a better grasp of ES6 Promises, I decided to tackle this particular challenge:

There are three divs: div.red, div.green, and div.blue. They need to be displayed sequentially, each with a gradual increase in opacity through an async task using setInterval.

The objective is to execute 3 async tasks in sequence.

Below is the code snippet I wrote. Unfortunately, it encounters an issue during the rejection stage and throws a TypeError: undefined is not a function {stack: (...), message: "undefined is not a function"}

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style type="text/css">
    div{ width:100px; height:100px; opacity:0; }
    .red{ background:red; }
    .green{ background:green; }
    .blue{ background:blue; }
  </style>
</head>
<body>
<div class="red"></div>
<div class="green"></div>
<div class="blue"></div>
<script type="text/javascript">
    function appear(div){
        console.log("appear");
        console.log(div);
        return new Promise(function(resolve, reject){
            console.log("promise");
            console.log(div.attr("class"));
            var i = 0;
            var loop = setInterval(function(){
                if (i == 1){
                    clearInterval(loop);
                    console.log("animation end");
                    resolve(true);
                }
                div.css({"opacity": i});
                i+=0.1;
            },100);
        });
    }
    $(document).ready(function(){
        var divList = []
        $("div").each(function(){
            divList.push($(this));
        });
        console.log("start");
        (function(){
            return divList.reduce(function(current, next) {
                return appear(current).then(function() {
                    return appear(next);
                }, function(err) { console.log(err); }).then(function() {
                    console.log("div animation complete!")
                }, function(err) { console.log(err); });
            }, Promise.resolve()).then(function(result) {
                console.log("all div animation done!");
            }, function(err) { console.log(err); });
        })();
    });
</script>
</body>
</html>

Answer №1

When you encounter the issue of calling appear(current), keep in mind that current refers to the promise representing the latest step in your chain, not the div itself. Initially, it will receive Promise.resolve(), which is not a jQuery object and lacks an .attr() method.

To resolve this, consider using:

$(document).ready(function() {
    console.log("start");
    $("div").toArray().reduce(function(currentPromise, nextDiv) {
        return currentPromise.then(function() {
            return appear($(nextDiv));
        });
    }, Promise.resolve()).then(function() {
         console.log("all div animation complete!")
    }, function(err) {
         console.log(err);
    });
});

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

Refreshing datatable information - parsing JSON into table rows

My challenge is with a table that is initially server-side rendered. I am looking for a way to refresh the data in the table upon a click event. The issue lies in how to link specific JSON object properties to specific columns. The JSON object contains a ...

What is the most effective way to display a success notification?

After updating the data in my application, I want to display a success message. Although the Success function is functioning correctly, the message itself is not appearing. When I click on the save() button, a small alert box pops up but the message fails ...

Issue with adding a video to a playlist using Youtube API

While I have successfully implemented GET requests using the Youtube API v3, I am encountering difficulties when trying to make a POST request to add a video to a playlist. Despite trying various approaches such as including the key in the query string, pl ...

bespoke JavaScript confirmation dialogue box

After customizing a confirmation box for the logout feature, I encountered an issue. When the user presses cancel, the box closes and control remains on the same page as expected. However, when the user clicks yes to logout, nothing happens. Could anyone p ...

Python Selenium: Cannot Click on Element - Button Tag Not Located

TL,DR: My Selenium Python script seems to be having trouble "clicking" on the necessary buttons. Context: Hello. I am working on automating the process of logging into a website, navigating through dropdown menus, and downloading a spreadsheet. Despite ...

Using only the $http.get method, you can easily retrieve data in a simple

Here is my message from JSP, I am attempting to extract information from the response. $http.get('url.jsp', data).then(successCallback, errorCallback); I encountered an issue with "data is not defined" https://i.sstatic.net/NX60Y.png Is there ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Switching up icons using React Spring - a step-by-step guide!

Is it possible to change the icon when I click on it using react spring? For example, if I click on " ...

Are Global variables supported in the EXT JS framework?

When working with Java and C++, it is common practice to store a variable globally so that its value can be accessed from anywhere within the project. For example, if I am working inside a class named Residence and saving an INT as the residenceNumber to a ...

Unable to get the Gtranslate function to function properly within the drop-down menu

Currently, I am using Gtranslate.io languages on my website with flags displayed without a drop-down menu. Everything is running smoothly but now I am looking to enhance the user experience by placing the flags inside a drop-down list. I want English to ...

An application using AJAX that supports multiple languages

I am currently developing a web application that heavily relies on JavaScript and AJAX. One of the requirements for this app is to support multiple languages. For server-side translation, I have implemented a template engine in PHP which handles translati ...

Tips for displaying ajax search results in Laravel views

My attempt to send a JSON response via AJAX to my Laravel view is not yielding any successful results. public function viewMasakanAjax(Request $request) { if($request->ajax()) { $alberMasakan = Masakan::where('alber_nama_masakan&ap ...

Is there a way to ensure that my function does not return undefined and instead returns a specific value?

Currently, I am facing a roadblock while attempting to conquer the Rock-Paper-Scissors challenge proposed by The Odin Project. Some confusion arises as my function playRound seems to be returning undefined when executed. Any insights or assistance in res ...

Spin a sphere by clicking on a link using three.js

I've designed a spherical object and have a group of links. I'm looking for a way to manipulate the position or rotation of the sphere by simply clicking on one of the links. Despite extensive searching, I haven't been able to find an exampl ...

What is the reason that textContent assignment does not function properly when used with HTML tags?

I have been attempting to insert additional text into an existing element using the textContent property. However, when I use the += operator for addition assignment, it seems to strip away the formatting of pre-existing tags like b. I expected that the ne ...

Is it possible to utilize PropTypes to indicate that a prop is of type Promise?

Using PropTypes can aid in debugging by providing warnings when expectations are not met. Additionally, they serve as a helpful tool to clearly express how a component should be used. If I have a component that requires a prop with a value that could pote ...

What methods does Flipkart employ to access DOM elements for integration testing purposes?

Something that caught my eye recently is that Flipkart uses mostly random class names in their DOM elements, reminiscent of the styled-components library. I'm curious to know how they go about accessing these DOM elements for integration testing. UP ...

Performing XMLHttpRequests and ajax requests inside a foreach loop

I am facing a issue with echoing the decoded array using var_dump. Each time I click the button, a unique xmlhttprequest and ajax call should get executed for every row. However, in reality, the ajax doesn't work as expected. Upon examining the source ...

Prioritizing TypeScript React props in VS Code IntelliSense for enhanced development

Imagine having this efficient component that works perfectly: import clsx from "clsx"; import React from "react"; interface HeadingProps extends React.DetailedHTMLProps< React.HTMLAttributes<HTMLDivElement>, ...

Information sent to a slot does not trigger a response

Trying to create a mobile-friendly chat app, I want to hide the new message button during conversations and use a different button on desktop. In addition, I have a dialog for creating new chat groups. <v-dialog transition="dialog-top-transition&qu ...