Ways to include additional assurances depending on a specific circumstance

When my code is executed in edit mode, I have a selection of API calls that need to be made, as well as one specific API call that must be made in both create and edit modes.

Here is the current code snippet:

// other controller code
var config = {};

var image = {
  dc: { name: 'abc' },
  cl: { name: 'def' },
  ds: { name: 'ghi' },
  net: { name: 'jkl' }
};

// Activate loader
vm.loading = true;

// Always retrieve list of DCs, whether in create or edit mode
promise = getDc()
  .then(function(response) {
    config.dc = response.data.dc;
    return $q.resolve(response.data.dc);
  }, function() {
    return $q.reject('Failed to get DCs');
  })

// In edit mode, fetch lists of Cls, Nets, and DSs if necessary.
// These are all dependent on the list of DCs.
if (editMode) {
  promise
    .then(function(dcs) {
      image.dc = _.find(dcs, { name: image.dc.name });

      return $q.all([
          getCl(image.dc),
          getNet(image.dc)
        ])
        .then(function(response) {
          config.cl = response[0].data.cls;
          config.net = response[1].data.nets;

          return $q.resolve([response[0].data.cls, response[1].data.nets]);
        }, function() {
          return $q.reject('Failed to get cls or nets');
        });
    })
    .then(function(lists) {
      image.cl = _.find(lists[0], { name: image.cl.name });
      image.net = _.find(lists[1], { name: image.net.name });

      return getDs(image.dc, image.cl)
        .then(function(response) {
          config.ds = response.data.ds;
          return $q.resolve(response.data.ds);
        }, function() {
          return $q.reject('Failed to get DSs');
        });
    })
    .then(function(dss) {
      image.ds = _.find(dss, { name: image.ds.name });
      return $q.resolve();
    });
}

promise
  .then(function() {
    // Open modal here
  })
  .catch(function(error) {
    // Print any errors
    console.error(error);
  })
  .finally(function() {
    // Deactivate loader
    vm.loading = false;
  });

In create mode, the modal will open directly after fetching the DCs. However, in edit mode, additional elements need to be loaded first.

The issue lies in the fact that the loader only shows until the loading of the DCs is complete, and the modal opens right after. It does not wait for other elements to finish loading.

Any suggestions?

Answer №1

The chain of promises you established following if (editMode) { stems from the original promise, but it operates separately instead of replacing it. This entire sequence is executed regardless of the logic set after the if() statement. To resolve this issue, reassign the promise:

if (editMode) {
  promise = promise
    .then(function(dcs) {
    ...
}

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

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

Creating a conditional interface based on props in TypeScript: A step-by-step guide

What is the most effective way to implement conditional props in a component that can be either a view or a button based on certain props? Let's take a look at an example called CountdownButtonI: class CountDownButton extends Component<CountdownBut ...

The Dysfunction of JQuery UI 1.12.1 Autocomplete

I am encountering some challenges with implementing JQuery UI. The version of JQuery UI I am using is 1.12.1, the latest one available. I have downloaded the autocomplete feature along with all other necessary widgets. In my project, I have placed jquery ...

Excessive JSON formatting is consuming an excessive amount of storage space

As I work on developing a website that recommends locations to visit in NYC, I am facing an issue with saving JSON data in local storage. My goal is to allow users to add their own suggestions and eventually integrate MongoDB into the site. To build the si ...

What is the best way to retrieve the JQuery property from within a regular JavaScript function?

I am facing an issue with a function that takes an array as input and manipulates its values. The problem lies in the fact that the array is composed of JQuery nodes (specifically spans), and I retrieve the span value by utilizing the .text() method in jQu ...

GAS: What strategies can I implement to optimize the speed of this script?

I have a sheet with multiple rows connected by "";" and I want to expand the strings while preserving the table IDs. ID Column X: Joined Rows 01 a;bcdfh;345;xyw... 02 aqwx;tyuio;345;xyw... 03 wxcv;gth;2364;x89... function expand_j ...

The error message "TypeError: usert.addItem is not a function" indicates that

Currently in the process of developing a discord bot using discord.js, sequelize, and sqlite for database management. Encountering an issue with a custom function that is not being recognized as defined by the terminal, despite me confirming its definition ...

Leverage the power of JavaScript validation combined with jQuery

Hello, I'm relatively new to the world of Javascript and jQuery. My goal is to create a suggestion box that opens when a user clicks on a specific button or div element. This box should only be visible to logged-in users. I have some knowledge on how ...

Can the Flash Configurator be converted to PHP or Javascript?

Considering converting this flash application into either PHP or JavaScript. Take a look at the example: In PHP, the page reloads every time the customer selects a color. With AJAX, it's challenging to pass the selected value to PHP. Are there any ...

Encountering deployment problems with React and TypeScript involving router on Github Pages

After successfully running locally, I encountered a 404 error when deploying the website using "npm run deploy." My application is built with React and TypeScript, utilizing react-router-dom BrowserRouter for navigation between pages. I've spent 7 h ...

What is the best way to hide the background of an extension's HTML?

Currently, I am working on developing a Chrome extension for a university project. However, I am facing challenges in making the background or body of the extension's HTML completely transparent to achieve a cleaner interface. The issue specifically l ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

Requesting information asynchronously returns a positive response

I wrote the following code: if (venue_exists(instagramUserID)){ alert('A'); }else { alert('C'); } function venue_exists(instagramUserID) { $.get( "/venues/" + instagramUserID, function( ...

Obtaining JSON Data Using WinJS.xhr():

I'm encountering difficulties with retrieving chat messages using winjs.xhr: function getMessage() { var time = MESSAGE_RETURNED.unixtime; if (time == 0) { time= window.parent.SESSION.unixtime; } WinJS.x ...

Pressing the button on the form has no effect

I am testing a login screen using NodeJS, but I am facing an issue where the submit button does not redirect to the dashboard screen as intended. What could be missing in the code? The submit button should direct to the dashboard screen that I have created ...

The method window.getComputedStyle retrieves the CSS max-height property containing an unresolved calc() function

Has anyone encountered a challenge with a function related to Angular in their project? Here is a snippet of the code causing issues: console.log(window.getComputedStyle(this.frontLayer.nativeElement).maxHeight); And within the component template: <di ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

What is the best way to launch a Popup window that spans from the top to the bottom of the screen?

I'm attempting to create a popup window that stretches from the top of the screen to the "applications" bar in Windows. Here's the code I'm using: function windowOpener(windowHeight, windowWidth, windowName, windowUri) { var windowHeight = ...

The checkValidity function fails to identify incorrect "tel" input

In my form, I am using the checkValidity function to validate inputs. However, I have encountered an issue where the validation only works when an input with the required attribute is missing a value. It doesn't work if there is a value type mismatch, ...