Tips for building a JavaScript promise chain using an array function

I encountered a strange problem while working on a JS promise chain. When using an arrow function with parentheses in the promise, I am not getting the expected value. Instead, it gives me an 'undefined' value in the second 'then'.

Here is the JavaScript code:

let x = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f78498999283cec0c7b7909a969e9bd994989a">[email protected]</a>');
    }, 2000);
});

function y(email) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(email);
        }, 4000);
    });
}

x.then((res) => {
    y(res);
})
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
    });

However, when I removed the ()=>{} syntax inside the .then, I received the correct output.

Here is the corrected code:

let x = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2c30313a2b66686f1f38323e3633713c3032">[email protected]</a>');
    }, 2000);
});

function y(email) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(email);
        }, 4000);
    });
}

x.then((res) => y(res))
    .then((res) => console.log(res))
    .catch((err) => console.log(err));

Could someone offer assistance with this issue?

Answer №1

To properly chain promises, it is essential to return a Promise object. The following example demonstrates the correct implementation:

x.then((res) => y(res))
    .then((res) => console.log(res))
    .catch((err) => console.log(err));

The expression (res) => y(res) can be interpreted as:

(res) => {
   return y(res)
}

Subsequently, the result of the promise returned by y() is passed to the next .then method. To rectify your code, consider structuring it like this:

x.then((res) => {
    // perform calculations
    return y(res);
})
    .then((res) => {
        // handle result of y promise
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
    });

Answer №2

When you want to return something from a function using curly braces {}, you must use the keyword "return" like this:

x.then((res) => {
  return y(res);
});

With arrow functions, if no curly braces are added, the value immediately after => is returned, like in this example:

then((res) => console.log(res));

Answer №3

Appreciate everyone for sharing their insights. I have gained clarity on why my initial code didn't function as expected. Turns out, it was related to array functions and not promises!

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

Mastering the art of seamless navigation within a single page through the magic of

I have two HTML pages: "Login.html" and "index.html". Instead of a normal href linking, I want the user to navigate to "index.html" when they click on the login button. Furthermore, I want the index page to be displayed within the codes of login.html, cre ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

The onSubmit function is resistant to updating the state

Currently, I am facing a challenge while working on a form using Material-UI. The TextField component is supposed to gather user input, and upon submission, my handleSubmit() function should update the state with the user-entered information. Unfortunate ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...

Insert code into current webpage to delete the content

Hey everyone, I have a dilemma. I've been doing some searches on Ebay with worldwide results, but I want to filter out any results from China. Is there a way for me to incorporate a script that will exclude any listings containing the word "China" (sp ...

Using Three JS: Import an OBJ file, move it to the center of the scene, and rotate around it

I am trying to figure out how to load an OBJ file and translate its coordinates to the world origin (0,0,0) in order to make orbit controls function smoothly without using Pivot points. My goal is to automatically translate random OBJ objects with differe ...

Using React to retrieve information from an array stored in the state

Hello there, I'm currently learning React and I'm facing an issue with my code. Within my state, I have an array and a function called submitted. This function is used to push new data into the array. Everything seems to be working fine except f ...

Unable to populate an array using JavaScript

I am a newcomer to JS programming and I am eager to create my own script for more practice. However, I could use some assistance. To begin with, I have a basic array set up at the start of my script: Var viewportHeight = $(window).height(); contentTo ...

What is the best way to incorporate new data into localstorage in a React application?

My attempt to implement and add data into local storage has not been successful as it keeps updating the old data instead of adding new ones. Can someone please explain how to store an array of objects entered by a user in local storage using React JS? ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

I was working with node.js when I encountered the following issue: 'server' is declared but its value is never read.ts(6133) from the line "var server = app.listen(3000, listening);"

While working on the 8.6 lesson in the api2 folder, I encountered an error/bug. Upon inspection of my server.js file, I identified and rectified the issue. However, when I revisited the api1 folder for the 8.5 lesson, everything was functioning correctly a ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

support for wavesurfer.js in IE10 is not compatible with angular

In the process of developing an Angular application, I am utilizing the wavesurfer.js plugin to display media in wave format. While this functionality works smoothly in Chrome, it encounters issues in IE10 and IE11. Any assistance would be greatly apprecia ...

Logging an empty value in JavaScript when retrieving the value from an element using document

When I try to log the value of a text input field to the console, it appears empty. Any idea why this is happening? <input type="text" id="word"/> //JavaScript var userInput = document.getElementById("word").value; co ...

Encountering issues with the Justify props in Material UI grid – how to troubleshoot and solve the problem

Can someone help me troubleshoot why justify is not working in this code block? <Grid container direction='column' alignItems='center' justify='center' spacing='1'> <Grid item xs={12}> <Ty ...

Is there a way to assign API data as inner HTML using Lit?

Need help setting inner html of html elements with a get request Any suggestions on how to achieve this? import { LitElement, html, css } from "lit"; import { customElement } from "lit/decorators.js"; import axios from "axios" ...

can you explain the concept of a backing instance in react?

Although the concept of a "backing instance" is frequently mentioned in React documentation, I found it difficult to grasp its meaning. According to the React docs: In order to interact with the browser, you need a reference to a DOM node. By attaching ...

The toggle checkbox feature in AngularJS seems to be malfunctioning as it is constantly stuck in the "off"

I am trying to display the on and off status based on a scope variable. However, it always shows as off, even when it should be on or checked. In the console window, it shows as checked, but on the toggle button it displays as off Here is the HTML code: ...

What is the correct way to implement a text field using jQuery?

Having trouble getting a text field to show up on the stage of the pong game with the code below. Looking for some assistance with this, as it's my first attempt at using jquery and javascript. Thanks in advance for your help! <!doctype html& ...