Having trouble with JSON parsing in Promise execution

I am in the process of developing a Promise with the objective of adding up any numbers discovered within an array or JSON object.

The add() function is designed to receive a series of URLs as a string input and calculate the total sum of those URLs.

Here's my approach:

I've introduced a helper function named parse, which accepts a string (the URL) and should display the JSON object specified at that location.

My issue arises when looking at the section marked by $$$$, where the jsonObject correctly represents the parsed JSON object. However, moving on to the area indicated by **** right after calling parse, the parsedObj no longer reflects the accurately parsed JSON object.

For instance, if I try to parse a JSON object that includes [1, 2, 5, 4], I'll receive jsonObject = 1,2,5,4 while parsedObj = [object Promise].

Why does parsedObj show an array of [object Promise] instead of 1,2,5,4?

Answer №1

parse(url: string): any will return a Promise instead of your jsonObject

Therefore,

                Log.trace("url: " + s.toString());
                let parsedObj = that.parse(s);
                Log.trace("parsedObj: " + parsedObj); // ****

This process is truly asynchronous. To obtain the jsonObject, you need to do the following:

parsedObj.then(function(jsonObject){
                for (var element of jsonObject) {
                    if (element.isNumber()) {
                        sum += element;
                        countNums++;
                    }
                    Log.trace("sum: " + sum);
                }

                Log.trace("sum: " + sum);
})

You should keep track of your parsedObj (Promises) in an array so that you can use Promise.all() to fulfill your parent promise once all the work is complete

Answer №2

It seems like you may be assuming that parse() will automatically return the resolved value just because there is a Promise.all() in your code.

Your code appears to be quite complex and relies on the deferred antipattern, so I have simplified it for you.

parse(url: string): any {
    let rp = require('request-promise-native');
    return rp({ uri: url })
        .then(
            JSON.parse, 
            function(err){ 
                throw "Error: URL could not be retrieved" 
            }
        );
}

add(urls: string[]): Promise<number> {
    return Promise.all(urls.map(this.parse))
        .then(function(arrays) {
            let emptyArray = [];
             //flatten
            let numbers = emptyArray.concat.apply(emptyArray, arrays)
                //remove non-numeric entries
                .filter(function(v){
                    return v.isNumber();
                });

            if(0 === numbers.length){
                throw "Error: No number was provided";
            }

            //sum
            return numbers.reduce(function(a,b){ 
                return a+b;
            });
        });
}

However, I have omitted the logs from the code.

Do you have any questions?

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

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

Enhance your MongoDB with the power of JQuery and ExpressJS combined with the magic

I've successfully implemented a delete function using type: 'DELETE', and now I'm attempting to create an UPDATE function. However, I'm unsure if I'm approaching this correctly. Here's the code I've written so far: ...

Error: The property 'parentNode' cannot be read because it is null

I wanted to test if my laptop can handle WebGL by loading examples from my instructor's webpage. The examples on the webpage worked fine, just showing a square within a square. I then decided to copy the exact codes into a notepad text editor, saved t ...

A blank page is appearing mysteriously, free of any errors

I have experience with ReactJs, but I am new to Redux. Currently, I am working on implementing an async action where I call an API and display the data received from it. Initially, when all the Redux components (actions, reducers, containers) were on a sin ...

How to turn off automatic password suggestions in Chrome and Firefox

Currently, I have integrated a 'change password' feature which includes fields for 'old password', 'new password', and 'retype password'. However, the autocomplete feature is suggesting passwords from other user acco ...

Using TypeScript to map over unboxed conditions: transforming OR operators into AND operators

I am working with an array that has multiple objects containing functions foo. My goal is to create a new object signature with a function foo that inherits all the signatures from the array item foo functions. let arr = [ { foo: (a: 'a') = ...

Exploring the intricacies of managing nested data in a Firebase Database (web)

I understand this question may have similarities to others already asked, so my apologies in advance. I am seeking a clear, up-to-date solution that aligns with my expectations. If I have an object labeled "Item One", how can I retrieve the array of "subI ...

store user settings in local storage

After writing some code with a link that toggles text visibility upon click, I now want to incorporate saving this state in web storage so that it persists upon page reload. As a beginner in JavaScript and HTML, this task has proven challenging for me. Th ...

Object-oriented programming in JavaScript allows for the passing of variables to a parent class using $

I am attempting to transfer variables from an XML file to the parent class in JavaScript. The code follows Object-Oriented Programming principles, with a class named "example" and a method called getData(). The issue I'm encountering is that the AJAX ...

After reaching a total of 20 entries, req.body will automatically convert the array into an

I have the ability to dynamically add properties to my form: <form action=""> <div class="property"> <label>Name : <input type="text" name="properties[1][name]"></label> <label>Order : <input type="text" na ...

Include a search button within the search box of the Custom Search Engine

Can anyone help me with adding a search button to my HTML code? I've tried implementing it, but when I try to search something on a website like YouTube, the results show up without displaying my search query. How can I fix this issue and what changes ...

Remove console.log and alert statements from minified files using uglifyjs-folder

Currently, I am minifying multiple files in a directory using the uglifyjs-folder feature within my npm configuration in the package.json file as shown below: "uglifyjs": "uglifyjs-folder js -eyo build/js" The process is effectively minifying all the fil ...

Vue.js seems to be leading me down a long and steady path of progress at a snail

I've exhausted all efforts to resolve the file paths for Home and App. I even turned to AI to help me out, but still no luck. Code snippet from main.js in the src folder: import Home from '@views/Home.vue'; // Using alias import App from ...

We'll show you the steps to properly organize a set of radio buttons created dynamically within a 'controlgroup' using jQuery Mobile

I am facing an issue with grouping dynamically generated radio buttons into a jQuery Mobile control group. I generate the radio buttons and append them to a div, but they are displayed separately even though the wrapping div contains a 'controlgroup&a ...

Implementing a universal timer for tmi.js and discord.js integration

I am currently working on a Discord bot that monitors multiple Twitch chats for commands and executes them on Discord using tmi.js and discord.js. Everything is functioning as expected, but I am facing an issue with implementing a global cooldown on the ...

How can I extract the {"Europe":{"France":"Paris","UK":"London","Germany":"Berlin"}} JSON object in C# and retrieve the actual object values as keys?

Update: I am in the process of reformulating my question. I have a database as a data source for continent, country, and capital lists. From this data, I need to create a JSON object with a specific structure. I need to design a Dto (Data Transfer Object) ...

JavaScript threw an error with message: 'Unexpected identifier' that was not caught

Upon launching Web Developer in Firefox: SyntaxError: missing } after property list note: { was opened at line 7, column 7 ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

Jackson Annotation Choice to exclude field name during serialization

Hey everyone, I need some assistance with removing the property name during the serialization of a Pojo to json. Here is the class I am working with: public class Field { private List<SubFieldItems> subFieldItems; public List<SubFieldIt ...

Deliver a response to recipients through the "button" feature within the WhatsApp cloud API

I'm working on building a chatbot for my booking company. Here is an outline of my initial bot flow: const axios = require("axios").default; function initialize_bot(message, phone_number, access_token, sender, username) { if (message === ...