The console is displaying a promise that is pending, rather than the desired data

Here is the content of my file:

 'use strict'
import * as moment from "moment";
import { Report} from "./Report";
import { Timeframe} from "./Timeframe";
import { ReportComparison } from "./ReportComparison";

function test(firstFrom: string, firstTo: string, secondFrom: string, secondTo: string) {


    var pastReport = new Report(new Timeframe(moment(firstFrom), moment(firstTo)));
    var laterReport = new Report(new Timeframe(moment(secondFrom), moment(secondTo)));

    var reportComparison

    function getData(pastReport: Report, laterReport: Report) {

        var later = function() {
            return new Promise((resolve, reject) => {
                laterReport.fetchData(data => resolve(data));
            });
        };

        var past = function() {
            return new Promise((resolve, reject) => {
                pastReport.fetchData(data => resolve(data));
            });
        };

        return Promise.all([later(), past()]).then(() => {
            laterReport.sort();
            reportComparison = new ReportComparison(pastReport, laterReport);

            return {
                pastReport: {
                    projects: reportComparison.pastReport.projects,
                    timeFrame: reportComparison.pastReport.timeframe,
                    totalAutomatedRuns: reportComparison.pastReport.totalAutomatedRuns,
                    totalManualRuns: reportComparison.pastReport.totalManualRuns

                },
                laterReport: {
                    projects: reportComparison.laterReport.projects,
                    timeFrame: reportComparison.laterReport.timeframe,
                    totalAutomatedRuns: reportComparison.laterReport.totalAutomatedRuns,
                    totalManualRuns: reportComparison.laterReport.totalManualRuns
                },
                trends: reportComparison.trends
            }

        });

    }

    return getData(pastReport, laterReport).then((res) => {
        return res;
    });

}



console.log(test("20170707", "20170707", "20170710", "20170710"))

In its current state, when I run console.log it displays Promise { <pending> } instead of the desired JSON object. I am wondering if my approach to dealing with asynchronous code is correct? Can anyone suggest a solution that would allow me to return the JSON object directly rather than a pending promise?

Answer №1

The function test does in fact return a promise. To retrieve the data, use the .then() method.

test("20170707", "20170707", "20170710", "20170710")
    .then((response) => {
         console.log(response);
    });

Answer №2

Indeed, promise will be received only by returning a promise from this point.

return getData(pastReport, laterReport).then((res) => {

    return res; //Perform callback here...
});

This is the main return value of your test function. You have indeed returned a promise, and remember that whatever is returned within the 'then' block will only be reflected in that particular function, not in the overall return value of the test. If you prefer not to alter your code, you can utilize a callback.

Alternatively, modify it to

return getData(pastReport, laterReport)

and adjust your test call like so

test(...).then((res)=>{ 
})
Or like this
var a = await test(...)
Then the test will provide data as output.

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 Angular, a function can be called recursively directly from within the HTML

I'm struggling with loading an image because the method getUserProfileImage() is getting triggered multiple times within a loop. Is there a way to ensure the method is only called once during each iteration? I understand that this issue is related to ...

What could be the reason for my form submission redirecting to the PHP page?

(I recently discovered that I could edit and reopen the post I had previously made. Feeling a bit confused about the process...) After submitting the form, the email is sent successfully, but then I am redirected to my php page displaying the number 0. Th ...

Uncertainties surrounding the complexity of this multi-stage form

Exploring this multi-step form I have a couple of questions: 1) Is there a way to transfer the value from the first step to the second step of the form? 2) How can I ensure that the datepicker value is not empty (to prevent user progress in the firs ...

The code functions properly when run locally, however, it encounters issues when deployed

When testing the following lambda code locally using Alex-app-server, everything works perfectly fine. However, when I publish it and test on AWS Lambda, it gets stuck within the else statement. It prints the console log 'OUT PUBLISH' but doesn&a ...

The issue of JQuery recursion not properly focusing on a textbox

Can anyone help with a jquery focus issue I'm experiencing? My goal is to address the placeholder problem in IE by focusing on an element and then blurring it to display the placeholder. This functionality is being used in a modal form. Initially, e ...

Using AngularJS to access JSON files through the $http service

I'm experiencing difficulties reading data from my test.json file using the #http service. I have everything set up on a xampp localhost, but I can't seem to figure out what's going wrong. Here's the JavaScript code. Thank you in advanc ...

An instance of an object is being added instead of parameters

I'm having some trouble making a server call using promises. Whenever I try to add my parameters, they end up showing as 'object%20Object' Here's the code snippet for the call: import { Injectable } from '@angular/core'; imp ...

Using a Jasmine spy to monitor an exported function in NodeJS

I've encountered difficulties when trying to spy on an exported function in a NodeJS (v9.6.1) application using Jasmine. The app is developed in TypeScript, transpiled with tsc into a dist folder for execution as JavaScript. Application Within my p ...

Transfer the data for 'keys' and 'input text' from *ngFor to the .ts file

I am facing difficulty in creating a string with dynamically generated keys from *ngFor and user input text. Let me provide some code to better explain my need. <th *ngFor="let column of Filter" > <tr>{{ column.name }}: <input type="{{c ...

In functions, Typescript does not have the ability to automatically infer undefined or null checking

I'm facing an issue related to Typescript type checking while working with functions. Let's assume I have a Type called IBaseField and a variable of Type Array<IBaseField>. When trying to assign a value to this variable, I consistently chec ...

Designations for removing an item at a targeted subdirectory location

type Taillet<T extends any[]> = ((...t: T) => void) extends (( h: any, ...r: infer R ) => void) ? R : never; type NestedOmit<T, Path extends string[]> = T extends object ? { 0: Omit<T, Path[0]>; 1: { [ ...

Sharing parameters between functions in JavaScript

I have a working code but I want to modify the function getLocation to accept 2 arguments that will be passed to getDistanceFromLatLonInKm within the ajmo function. Currently, getDistanceFromLatLonInKm has hardcoded arguments and I would like to use variab ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

Exploring the concepts of AngularJS directives and resources

I've been experimenting with angularjs and rest service calls to display specific data sets, but I'm encountering challenges with custom directives and resources. Currently, I have a custom directive that loads a list of comments in an applicati ...

When using State.go(), the url in the address bar will update, but the HTML view will not be refreshed

Encountering an issue while working on Ionic with AngularJS, specifically with the routing system when attempting to create a login page. In the controller section of the code, I am trying to navigate to a welcome page called 'dash' using state.g ...

Utilize Bootstrap button dropdown to automatically assign a selected value to a list item

I have a form with a select box that transforms into a bootstrap button after the page loads. However, I am unable to set the selected value for the converted bootstrap button drop-down li. <button type="button" class="btn dropdown-toggle btn-default" ...

The page does not appear to be updating after the onClick event when using the useState hook

Having difficulty re-rendering the page after updating state using the useState hook. Although the state value changes, the page does not refresh. export function changeLanguage(props: Props) { const [languageChange, setLanguageChange] = React.useState( ...

I am experiencing difficulty in passing parameters to nested navigators

I have developed a TechInfo page and a ProfileInfo page. The ProfileInfo Page is nested inside a Drawer Navigator. I want to display some information from the TechInfo page and some from the ProfileInfo page when I enter our info and press a button. Howeve ...

Creating a Gmail share button in AngularJS: A step-by-step guide

I created a messaging web application using AngularJS, and I successfully added functionality to share messages via email using the "mailto" link. However, this method only works if the user has an email client installed. Now, I am looking for a solution ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...