Mastering the art of using either promises or callbacks properly

Attempting to retrieve the result of a variable after completing all asynchronous processes in a function. I've discovered that I need to use promises for this, so I spent today learning about them.

I've implemented promises in my function and consulted various tutorials, but I keep encountering an error. It seems like there might be an issue with how I'm handling kpiDefault or the implementation of my kpiAverage function. Additionally, using coffee script could potentially introduce syntax errors.

Below is my code snippet for kpiAverage:

kpiAverage = (period, kpiName, params) ->
    result = $q.defer()
    Sads.shops.getList(params).then (data) ->
      shops = data.map((d) ->
        new ScopeShopWithMetrics(d, $scope.organizations.current)
      )
      $q.all(shops.map((d) ->
        d.getAverages(period)
      )).then( ->
        shopSum = 0
        i = shops.length
        shopSum += shops[i]["metrics"][kpiName]["value"] while i--
        shopAverage = shopSum / shops.length
      ).then((shopAverage) ->
          result.resolve(shopAverage)
          result.promise
        )

Now let's take a look at the problematic code:

kpiDefault = kpiAverage(period7, "visits", testParams).then((shopAverage) ->
   shopAverage
  )

When I execute this code, although it doesn't throw an error, the output isn't a number; instead, it appears to be a promise object.

kpiDefault = kpiAverage(period7, "visits", testParams)

Output:

Object {then: function, catch: function, finally: function}

Edit:

It seems I've been misusing promises all along, leading to further confusion. My goal is simply to return the value after finishing the asynchronous process, yet I'm more puzzled than before.

Upon reviewing the code, I identified and resolved the cause of the error (an old uncommented code), yet I'm still receiving a promise object as output.

Answer №1

// This function in my Factory retrieves data.
result.retrieveData = function(){
var deferred = $q.defer();

return $http.get( constant.adressApi + 'data', { cache : true, params :{ 'limit' : 50 } } )

.success(function (data) { deferred.resolve(data); })
.error(function(error){ deferred.reject(); });

return deferred.promise;
};

    // Calling the function from the factory service.
    presentationService.retrieveData()
    .then(function(result){
    $scope.result = result.data;
    });

This is how I use promises easily and hope this can help you.

Creating a deferred or future object, returning it at the end of the function to represent the result. When the asynchronous function returns the result successfully, the deferred gets resolved triggering the .then() callback where you can access the result. If there's an error, the .error() function handles it by rejecting the deferred.

Short Answer: Based on your code, it seems like you are not resolving or rejecting your deferred, which could be why you are seeing the output as:

Object {then: function, catch: function, finally: function}

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 updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

What is the best way to alternate between two CSS stylesheets when using jQuery-UI?

Just getting started with jQuery and javascript and decided to test out 2 different jQuery-ui stylesheets in a simple .html file. The goal is to have the example dialog open with the "flick" stylesheet and the datepicker within the dialog open with the "u ...

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

String casting for large JavaScript integers may require rounding to function properly

When trying to pass a large integer to a function from an onclick event in HTML, I always encounter issues with rounding. Despite using bigInt libraries, I still struggle to pass the full number accurately and would prefer a simple string casting method. ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

Secure Access: Passport.js User Verification & Authorization

Recently, I successfully developed my first User login and authentication system using Passport.js. While the system works as intended, I am struggling to fully comprehend the code itself despite reading numerous articles and examples online. I would great ...

Is there a way to utilize nodemon without having to install it through npm?

I'm having trouble with my network not allowing me to use npm install. Is there another way for me to install and use nodemon? I've noticed that Node only runs after setting PATH variables on Windows. I attempted to set the path for nodemon, but ...

``Changing the value of the radio button does not update the ng-model variable

I have encountered an issue with my code. Upon page load, the radio button is checked but the ng-model value session.payment does not get updated automatically. I have to manually select it again for the update to take effect. <li ng-repeat="method i ...

Is it possible that activating the alert() function within a Node.js script could cause the server to freeze completely?

Given that Node.js operates on a single thread, is there a risk of freezing the entire server by calling functions like alert(), which typically wait for user input? Does Node.js have mechanisms in place to prevent such issues? ...

After activating the rewrite feature on Tomcat valve, JavaScript is loading twice

I've implemented the Tomcat rewrite valve in my single-page application to direct all requests, except for static resources, to my index.html file. Here is what my rewrite.config looks like: RewriteCond %{REQUEST_URI} (?!.*\.(?:jpg|png|css|js|js ...

The "scrollTop" function seems to be malfunctioning in Firefox but works perfectly fine in Chrome. Is there a way to fix this issue?

Issue with scrollTop in Firefox jQuery(window).scroll(function(){ var NextScroll = jQuery(this).scrollTop(); if (NextScroll >= 800){ jQuery('#logomacchia').addClass("maccancello"); } else { jQuery('#logomacch ...

Is there a way to trigger the onclick event while dragging the div?

Exploring a Div: <div id="up" onmousedown="handleMouseDown('url(/scanToUserBox/img/cpt_subfunc_005_prev_p.png)', this)" onclick="changePage('up')"> </div> Upon clicking the div, the onmousedown event is trig ...

Update the text label to contain an input checkbox element within

I encountered this snippet of HTML in my form: <label class="ideal-radiocheck-label" onclick=""> <input id="pagamento_8" class="_input " type="checkbox" onclick="half(this,value);" checked="" value="980" name="pagamento[]" style="position: ab ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

Is it possible to use speech recognition on browsers besides Chrome?

Is there a way to utilize a microphone with JavaScript or HTML5 without relying on Flash technology? I was able to achieve this in Chrome by using webkit-speech, but I am looking for solutions that will work in other browsers as well. Any suggestions wou ...

The video is not displaying on the webpage when connected locally, but it appears when the source is a URL

Recently, while practicing some basic tasks on a cloud IDE called Goorm, I encountered an issue with displaying a video on a simple webpage. The EJS file and the video were located in the same folder, but when I set the src attribute of the video tag to "m ...

Angular and Express: Automatically redirecting to the previous page after user login

A question similar in nature can be found here, although not directly relevant to my situation. Within my Single Page Application, I am implementing PassportJS for user authentication. There are multiple routes that necessitate user login. The routing is ...

Utilizing NodeJS to Refine JSON Data

I am working with a JSON array that consists of multiple objects. My goal is to retrieve objects that have a specific value, such as returning [ service_wog: { count: 48, popular: false, code: 33, price: 20, id: ...

What is the best way to display a segment of an SVG on a Canvas element?

Main Issue: The main objective here is to display a specific part of an SVG image on a fixed size Canvas element within a web page. Approach I Tried: After considering various options, such as using CanVG, I thought about utilizing the viewBox attribute ...

Unsynchronized state of affairs in the context of Angular navigation

Within my Angular project, I am currently relying on an asynchronous function called foo(): Promise<boolean>. Depending on the result of this function, I need to decide whether to display component Foo or Bar. Considering my specific need, what woul ...