Navigating through nested promises can be a daunting task within the world of JavaScript and Angular

Function 2 relies on the return of Function 1, while Function 3 uses both returns. How can I clean up this process? Currently, Function 3 is only giving me undefined values.

Below are my 3 functions:

Function1

$scope.nombreCompetencesATraiter = function(){
var nbr = 0;
        notesService.getNotesByCollaborateurId($scope.idCollaborateurSelectionne).then(function(data){
            $scope.myNotes = data;
            angular.forEach($scope.myNotes, function(valueNote, keyNote) {
                if ((valueNote.status === "EN_ATTENTE_DE_VALIDATION") || (valueNote.status === "EN_ATTENTE_DE_SUPPRESSION")){
                    nbr++;
                }
            })
            console.log(nbr);
            return nbr;
        })
    }

Function 2

$scope.affinerConfigBoutonsCompetences = function() {
        nbCompetenceATraiter = $scope.nombreCompetencesATraiter();
        if (nbCompetenceATraiter == 0){
            $scope.radioModelFilterToutesLesCompetences = true;
            $scope.radioModelFilterCompetencesAValider = false;
        }
        else{
            $scope.radioModelFilterCompetencesAValider = true;
            $scope.radioModelFilterToutesLesCompetences = false;
        }
    }

Function 3

$scope.affinerConfigBoutonsCompetencesThen = function(){
        $q.all([$scope.nombreCompetencesATraiter(), $scope.affinerConfigBoutonsCompetences()]).then(function(value) {
            console.log(value[0]);
            console.log(value[1]);
        })
    }

Any advice would be greatly appreciated. Thank you!

Answer №1

After reviewing Luillyfe's feedback, it appears that there are some mistakes in your code. Here is a more concise way to resolve the dependency:

var f1 = () => new Promise( resolve => resolve('value1'));
var f2 = ( value1 ) => new Promise( resolve => resolve('value2'));
var f3 = ( value1, value2 ) => new Promise( resolve => resolve('done'));

f1()
    .then( value1 => Promise.all([ value1, f2( value1 ) ]) )
    .then( ([ value1, value2 ]) => f3( value1, value2 ))

Remember, Promise.all can be used with non-Promise values as well. It will simply pass them directly to the next then block.

Answer №2

Task 1 needs a return statement added before calling noteService

$scope.countPendingSkills = function() {
var count = 0;
  return notesService.getNotesByCollaborateurId($scope.idCollaborateurSelectionne)
    .then(function(data) {
      $scope.myNotes = data;
      angular.forEach($scope.myNotes, function(valueNote, keyNote) {
        if ((valueNote.status === "EN_ATTENTE_DE_VALIDATION") || (valueNote.status === "EN_ATTENTE_DE_SUPPRESSION")) {
          count++;
        }
      })
      console.log(count);
      return count;
  })
}

Task 2

$scope.updateSkillButtonsConfig = function() {
  return $scope.countPendingSkills().then(function (value) {
    pendingCount = value;
    if (pendingCount == 0) {
      $scope.showAllSkills = true;
      $scope.showPendingSkills = false;
    } else {
      $scope.showPendingSkills = true;
      $scope.showAllSkills = false;
    }
    return pendingCount; // value you want to return
  });
}

Task 3

$scope.updateSkillButtonsConfigThen = function(){
    $q.all([$scope.countPendingSkills(), $scope.updateSkillButtonsConfig()]).then(function(value) {
        console.log(value[0]);
        console.log(value[1]);
    })
}

Let's see how that works!

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

Facing the error "Routes not found in Angular 2: ''"

Having an issue with my Angular 2 app (RC4) where upon opening the index.html file, I encounter the error message Error: Cannot match any routes: ''. I've seen this problem mentioned before, but none of the solutions provided seem to work fo ...

Development of Chrome Extensions, JavaScript dilemma

Hey there, I'm new to JavaScript and I've been diving into the world of creating Chrome extensions. I'm trying to set up a content script and browser action, but I'm struggling to get it up and running. I know I'm probably making a ...

Is using JQuery recommended for implementing onclick and onchange events?

Hello there, I'm completely new to the world of jQuery and currently facing a bit of confusion. Here's my dilemma: should I be utilizing jQuery with the onclick event or the onchange event for an element using something like this: $(selector).som ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

Tips for retrieving the return value from a function with an error handling callback

I am having an issue with my function that is supposed to return data or throw an error from a JSON web token custom function. The problem I am facing is that the data returned from the signer part of the function is not being assigned to the token const a ...

Show each text field individually in JavaScript

Is it possible to display text fields one by one upon button click? Initially, all text fields are hidden, but when the button is clicked, they should be displayed one after another with their visibility property set to visible? This is what I have attemp ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

What causes jQuery results to resemble a function?

When I create a jQuery wrapped set and insert it into console.log, the output appears as follows: I am aware that we can manipulate the console to display objects or arrays. For example, when we have: var obj = { 0: 'some', 1: 'dat ...

Tips for inserting a string into an array nested within an object stored in a state array

Currently, the variable sizeVariant is a string array and I am trying to append strings to it using an onClick event. The function findIndex seems to be working fine. However, there seems to be an issue with the concatenation section. It appears that using ...

Setting the texture for a loaded glb model using Three.js

After successfully loading a basic glb model created in SketchUp using Three.JS, I encountered an issue with displaying text on the model. The model includes a group identified as Text. Despite being able to load and visualize the model correctly in Three ...

Error: You forgot to close the parenthesis after the argument list / there are duplicate items

I have already tried to review a similar question asked before by checking out this post, but unfortunately, I still couldn't find a solution for my problem. Even after attempting to add a backslash (\) before the quotation mark ("), specificall ...

Combining data-target and ng-click for optimal functionality

Can someone help me troubleshoot why my modal popup is not appearing before the ng-click event gets executed? The ng-click event is functioning correctly, but the modal is not displaying. <a class="btn btn-primary" data-toggle="modal" data-target="#ad ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

Attempting to dynamically update the title of a Vue Meta page using a combination of a string and

In the blog application for my project using Nuxt JS 2.4.5, I am utilizing Vue Meta. I'm encountering difficulties while attempting to set the title along with a variable from data (), and it seems like something crucial is eluding me. Despite tryin ...

Changing the HTML Structure of the md-datepicker Component

I am currently utilizing the md-datepicker component on my webpage. I have a specific need to include a CSS class to the produced input element. Is there a method to alter the markup that is generated by md-datepicker? <md-content> & ...

Button activates SVG animation

Currently, I am working on an animation for a button using SVG. The animation utilizes the classes .is-loading and .is-success. However, when I click on the button, the animation does not execute as expected. I'm having trouble identifying the error w ...

Add the content of a JavaScript variable to a label without using any scripting

Is there a way to concatenate the value of a JavaScript variable with a label without utilizing jQuery? For example: Var global_message = "1234"; <label id="my-label">Test</label> I desire the concatenated value "Test1234" to be displayed o ...

Start by retrieving information and then sending properties to a different component

I have been struggling with this issue for more than a week now. Despite thorough reading of the Next.js documentation and extensive online research, I still can't figure out what's wrong. It seems like I must be overlooking something important, ...

What steps should I take to create a functional image scrolling effect similar to the one shown in this example?

Recently, I came across and was intrigued by the "image slide effect" featured on their homepage. The way the background image changes as you scroll up, leading you through different introductory slides before reaching the main content of the site caught ...

Finding the label that is linked to the current DIV or textarea by its "for" property

I am working on a project that involves two elements - a textarea and a div. Each element has a label attached to it using the "for" attribute in HTML. <textarea id="txta_1" class="txta" cols="40" rows="3" onkeyup ...