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

Using Jquery to input selected dropdown values into a text input field

Currently, I am facing some challenges in achieving this task. My goal is to have the selected option from a dropdown list called programs_dropdown added to a text field named programs_input, with the option values separated by commas. For example: php, j ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Passing an array of selected values from Vue.js to a text area and adding them to the existing content

I'm facing a situation and I could really use some assistance. The image shows that there is a multiple select box on the left with numbers, and a text box on the right. My goal is to allow users to click on the house numbers in the select box and hav ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

Display options in Material-UI autocomplete only upon clicking the icon

Is there a way to display the options list only when clicking on the arrow icon as opposed to the textfield itself? I have reviewed the documentations without success in finding a solution. Example ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...

Invalid element type detected. A string was expected, but instead found undefined

Following a recent update of next-auth, an unexpected error has surfaced: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your compon ...

How can you loop through keys and values in a JSON object using JavaScript?

I am attempting to cycle through the JSON data below: { "VERSION" : "2006-10-27.a", "JOBNAME" : "EXEC_", "JOBHOST" : "Test", "LSFQUEUE" : "45", "LSFLIMIT" : "2006-10-27", "NEWUSER" : "3", "NEWGROUP" : "2", "NEWMODUS" : "640" } The keys in this JSON are d ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Exploring JSON objects within other JSON objects

As I work on my Angular App and implement angular translate for dual language support, I've encountered an issue with accessing nested items within my JSON object. After carefully constructing my JSON and verifying its validity, I attempt to retrieve ...

Retrieving the link to share for every video located in the Dropbox folder

My Dropbox folder contains a set of videos labeled "v1.avi, v2.avi, ....., vn.avi". I am looking to automate the process of extracting the share link for each video in the folder so that I can easily use it as a source value for HTML video. . . . Is ther ...

default selection in AngularJS select box determined by database ID

Here is the scenario: ... <select ng-model="customer" ng-options="c.name for c in customers"> <option value="">-- choose customer --</option> </select> .... In my controller: $scope.customers = [ {"id":4,"name":"aaaa", ...

jQuery - easily adjust wrapping and unwrapping elements for responsive design. Perfect for quickly undo

Within the WordPress PHP permalinks and Fancybox plugin, there are elements enclosed in an "a" tag like so: <a href="<?php the_permalink(); ?>" class="example" id="exampleid" data-fancybox-type="iframe"> <div class="exampledivclass"> ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

Identifying a specific field in a dynamically generated React.js component: Best practices

Currently, I am in the process of developing a form with an undetermined number of sensor fields. The front end has been successfully implemented and now my focus is on extracting user information from these dynamically generated component fields. Here is ...

Is it possible to dynamically load a specific div when the page loads, relying on the

I am using JQuery SlideUp and slideDown methods to toggle the visibility of panels. How can I load or display the first record's contact information as a default? Currently, it loads blank because I set the panel's display property to none: < ...

Encountered an issue while trying to use Figma's spellchecker extension

Despite following the instructions in the readme carefully, I am facing difficulties running the Figma spellchecker extension. Executing npm run build goes smoothly. But when I try to run npm run spellcheck, I encounter an error message in the console: co ...

css failing to load properly following javascript redirection

Upon clicking the button labeled id=cancel, the user will be directed to index.php. $('#cancel').click(function() { if(changes > 0){ $('#dialog-confirm').dialog('open'); }else{ window.location.href = ". ...

Developing a dynamic horizontal bar chart in d3 using a multidimensional array or nested JSON dataset

I am in the process of creating a straightforward d3 bar chart () by utilizing this specific nested json file. { "clustername": "cluster1", "children": [ { "neighborhoodname": "Shaw", "children": [ { "totpop2000": "1005", "children": [ ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...