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

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

Direct AngularJS to automatically reroute users from the login page to the welcome page

I am currently developing a web application where I need to redirect from the login page to the welcome page once the user id and password have been validated. <script> var app = angular.module('myApp', []); app.controller(&apo ...

Transform ajax functionality into jquery

I need help converting an AJAX function to a jQuery function, but I'm not sure how to do it. function convertToJquery() { // Create our XMLHttpRequest object var hr = new XMLHttpRequest(); // Set up variables needed to send to PHP file var ur ...

Encountering an Issue with NextJS on GAE: EROFS Error indicating a read-only file system

Trying to deploy a customized Next.js application into Google App Engine has hit a snag. The project runs smoothly locally and on Google Cloud Platform CLI, but upon successful deployment using gcloud app deploy, an error arises when opening the app. 2020 ...

Animating nested ng-repeat loops

Trying to animate a list of elements divided by rows (the parent ng-repeat) and columns (the child ng-repeat) has been quite challenging. While I was able to achieve the desired animation with individual ng-repeats, the same cannot be said for nested ng- ...

Implementing selective image loading with HTML and angularJS

This image reveals the issue at hand Within this HTML code snippet, some of my images are displaying on the webpage while others are not. How can I go about resolving this? <img src="img/uploadFiles/{{room.imageLocation.split('//')[6]}}/{{ro ...

PHP functions triggered by ajax fail to function properly when called repeatedly

I have encountered an issue with my javascript function that calls a php script upon clicking a button or link to retrieve data. Everything works well, except when I attempt to call data from an already outputted content via the same function. Let me share ...

Achieve full height without scrolling in React

I am facing an issue where the height:100% property is not working to fill the remaining area on the screen. A red outlined area represents the border radius, while the highlighted yellow space should have been filled: https://i.stack.imgur.com/ZQNkw.png ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

Creating dynamic flags with specific parameters using Pentaho and JavaScript

I am looking to optimize my code by finding a better way to achieve this. I have a variable called "hour" and I need to create flags for each hour of the day like so: if (hour == 0) {flag12AM = 'yes'} else {flag12AM == 'no'} if (hour ...

`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue? Here is my product schema: mongoose = ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

Is there a way to add an AngularJS module dependency without having to include it in the dependency array during the module definition process?

One way to ensure module dependencies are available is by defining them when declaring a module. For example: angular.module("myApp",["myDependentModule"]); As the application grows and modules accumulate more dependencies, it can become challenging to m ...

Trigger animation when the scroll position reaches 0.52 in Next.js using framer-motion

I’m working on a landing page and I have a section where I’d like to create a simple opacity animation using framer-motion. The issue is that these animations typically trigger as soon as you land on the page, but I want them to be based on scroll pos ...

Leveraging jQuery's element objects and the :contains selector allows for powerful

I need to search for a link that contains the word 'gathered'. Although I understand how to do it logically, I am having trouble writing the jQuery syntax for the selector: if (index === 3) { var $link = $('#rest').find('.tr ...

Discover the "route" of a JSON element using JavaScript

I've been struggling to retrieve the "path" of a specific AngularJS scope variable. My end goal is to utilize this "path" as the ng-model for dynamically generated forms. Below is my current code: my_code.js: var my_data = { name: "fred", numbe ...

Switching out text when hovering with Jquery or JavaScript

Is there a way to use jQuery or JS to make the text and icon disappear when hovering over a div, and replace it with "Read More"? I've looked at some guides but they only remove one line of text instead of clearing the entire div and displaying "Read ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...

Is it possible to dynamically add and remove items using React state?

I am currently working on implementing a dynamic queue of game players in my React state. The goal is to avoid hardcoding the number of players who can participate and achieve this state update using a JS FIFO queue. My objective is to create a player que ...

What is the best way to assign the initial value in a dropdown menu populated by a database table?

I'm new to AngularJS and I need help writing a function that can populate a select element with data from a database table. While I am able to fill the select element, I am struggling to set the default value for it. Here is my code: HTML : <div ...