Challenges Associated with Promises in JavaScript

I'm having trouble with the last line of code in my program and I need some help figuring out how to fix it. Specifically, I know that the second "then" statement needs to return resolve() but I'm not sure how to go about implementing this. Any tips or suggestions would be greatly appreciated!

let getNumber = new Promise((resolve) => {
    //API call
    EthereumNote.getAmountOfMyNotes(function(error, result) {
        if (!error) {
            let AmountOfMyNotes = Number(result)
            resolve(AmountOfMyNotes)
            console.log(result)
        } else
            console.error(error)

    })
}).then(result => {
    return new Promise((resolve) => {
        for (let i = 0, p = Promise.resolve(); i < result; i++) {
            p = p.then(_ => new Promise(resolve => {
                //Another API call
                EthereumNote.getMyNote(i, function(error, result) {
                    if (!error) {
                        let text = String(result[0])
                        let noteID = Number(result[1])
                        console.log(text)
                        console.log(noteID)
                        resolve()
                    } else
                        console.error(error)
                })
            }));
        }
    })
}).then(() => console.log('Hi!')) // Having trouble with this part

Answer №1

Avoid falling into the trap of using the Promise constructor antipattern. It's fine to create a new promise to encapsulate EthereumNote.getMyNote, but be cautious about wrapping it in a loop without ever resolving the outer promise.

Instead, simply return the chain of promises created in p:

let getNumber = new Promise((resolve) => {
    //API
    EthereumNote.getAmountOfMyNotes(function(error, result) {
        if (error) reject(error);
        else resolve(Number(result));
    })
}).then(amountOfMyNotes => {
    console.log(amountOfMyNotes);
    var p = Promise.resolve();
    for (let i = 0; i < amountOfMyNotes; i++) {
        p = p.then(_ => new Promise((resolve, reject) => {
            //API
            EthereumNote.getMyNote(i, function(error, result) {
                if (error) reject(error);
                else resolve(result);
            });
        })).then(result => {
            let text = String(result[0])
            let noteID = Number(result[1])
            console.log(text)
            console.log(noteID))
        });
    }
    return p;
}).then(() => {
    console.log('Hi!'); // this one now works
}, err => {
    console.error(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

Having trouble with installing NPM and ng commands, neither of them is working. I may have to uninstall everything and begin from scratch

Learning Angular and how to use the terminal is all new to me. I recently installed NPM and attempted to use ng serve, but encountered a series of issues. At this point, I am considering completely uninstalling everything so I can start fresh. I've d ...

Ways to remove any messages containing URLs that are not www.youtube.com or www.twitter.com

Recently, I have encountered a significant issue with Discord Scam Links in my server. I attempted the following approach: if(message.content.includes("discordscam.com")) { message.delete() } However, this method is not effective as it onl ...

Using Jquery to change an id with the .attr method may not always produce the desired results

I have a div element that functions as a button when clicked, with the ID of knight. Every time I click on any of the 3 buttons (including knight), it changes the ID of knight to elf (yes, I'm creating a game). I have a hover effect for knight usi ...

Display alert only when focus is lost (on blur) and a dropdown selection was not made

Utilizing Google Maps Places for autocompletion of my input, I am aiming to nudge the user towards selecting an address from the provided dropdowns in order to work with the chosen place. A challenge arises when considering enabling users to input address ...

Is locking Node and npm versions necessary for frontend framework projects?

Currently working on frontend projects in React and Vue, I am using specific versions of node and npm. However, with other developers contributing to the repository, how can we ensure that they also use the same versions to create consistent js bundles? ...

What is the best way to locate a div element with a specific style?

What is the method to locate a div element by its style? Upon inspecting the source code in IE6, here is what I find: ...an><div id="lga" style="height:231px;margin-top:-22px"><img alt="Google"... How can this be achieved using JavaScript? ...

Is it possible to incorporate several modules into nodeJS simultaneously?

I'm a beginner when it comes to NodeJS. I was wondering if it's possible for me to call 2 different JavaScript files using NodeJS and ExpressJS. The idea is to split the work, where I can focus on one file while my partner works on another. So, I ...

Ways to retrieve the text linked to a checkbox

Is there a way to access the text associated with a checkbox using its attribute? For example, in the code below, I want to alert the user with "Selected -- TextXYZ" when the checkbox is clicked. <form id="idForm" class="classForm"> <input type ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

What is the easiest way to locate the ID of an iframe embedded within a webpage?

Currently, I am focused on developing small JavaScript/HTML5 ads for a webpage. Each advertisement comes with its own iframe that occupies a specific size and space on the page. In order to accommodate an expandable ad that needs to surpass the predetermin ...

The Link component in the router dom should only be active when validation passes successfully

I am looking for a way to prevent the Link component in react-router-dom from functioning until all validations are successfully completed. Removing the link allows the validation to work as intended. I have come across something related to ifValidate, bu ...

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

Using a table row as a counter in HTML

I am looking for a way to automatically assign IDs to table rows using XSLT in a systematic manner. The idea is to have the ID consist of a string followed by a counter, like this: <table> <tr id="Row1"> # it can be only a number => id=" ...

Modifying various states within React using the useState() hook

Curiosity strikes me - what actually happens when I modify more than one state in a handler function? Will they be updated simultaneously, or will the changes occur sequentially? const [x, setX] = useState(0) const [y, setY] = useState(0) const handlerFu ...

jQuery struggles to process large response

I am currently developing an application that sends requests to a URL and parses the table found in the HTML response using jQuery. While this method works well for smaller amounts of HTML code, it runs into issues with larger datasets. The problem arises ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Transform an array of strings into an array of object IDs

Recently, I encountered an issue with transforming an array of strings into object IDs using mongoose type. Unfortunately, my attempt was unsuccessful as it seems the method only works for single string inputs, not arrays. let stringObjectIdArray = [&apos ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Adjusting the height of the search icon through the Jquery toggle action to create animated effects

While trying to create a search field with the click function (animate), I noticed an issue similar to what is seen in this example: . Whenever the search icon is clicked, it moves up and down unexpectedly, and I am uncertain as to why this behavior is occ ...

Currently, I am experiencing difficulties with two specific aspects of the website I am working on - the hamburger menu and the slideshow feature

I'm having trouble with the menu on my website. It's not functioning as expected - the dropdown feature isn't working, and two items are not staying in the correct position under the parent ul despite attempts to position them using CSS. Add ...