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

Embracing JQuery for Frontend Development with Node.js

I'm currently enhancing my node.js skills by utilizing express, and I've encountered a situation that is causing me some confusion. Essentially, when a user requests a webpage and the backend sends them the HTML page, how can I incorporate a Java ...

Develop a new object using NodeJS within a module for a function

I am working with a file named item.js exports.itemParam = function(name, price, url, id){ this.name = name; this.price = price; this.id = id; this.url = url; }; In my www.js file, I have imported item.js like this: var item = require('../m ...

When using AngularJS, you may encounter an issue with the injector causing

Hey there, I'm new to Angular and I'm trying to create a basic program but I keep running into an error. Controller: angular.module('myApp', []).controller('myCtrl', function ($scope ,HandleService) { $scope.AddCar = fu ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

In strict mode, duplicate data properties are not allowed in object literals when using grunt-connect-proxy

I recently started following a tutorial on AngularJS titled "Hands on Angularjs" by Tutsplus. In the tutorial, the instructor uses the grunt-connect-proxy package to redirect ajax requests to a Rails server running on localhost:3000. However, I believe the ...

Managing "post" requests in a one-page web application using node.js

Although there may be similar answers to this question, I am in search of something different. On the client side, I have a signUp form that will make a post request to the server with the username and password. On the server side, I authenticate the req ...

react-video-recorder` facing challenges with loading

I recently integrated react-video-recorder into my application. After checking out the demos on Stackblitz and Storybook hosted on Vercel, I was impressed with how well it worked in my browsers. However, when I added it to my codebase, the component would ...

Does it have .hasOwnProperty and a significant value?

Today, I encountered a tricky situation involving the JavaScript Object.hasOwnProperty method. I was working on a form that creates properties on an object. The issue arose when dealing with a select box that had a value selected and then reset back to it ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Encountering a ValueError when attempting to validate form fields with Django and JavaScript

I encountered an error while trying to validate a field using Javascript and Django. Error: ValueError at /insert/ invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/insert/ Django Version: ...

Step-by-step guide on how to activate a colorbox using a targeted Id or class

Below is the code I'm currently working with: <div class="hidden"> <div id="deletePopContent" class="c-popup"> <h2 class="c-popup-header">Delete Practice Sheet</h2> <div class="c-content"> <h3 ...

Tips for transforming every element of an array into its own array using JavaScript or Loadash

Hello, I have an array that looks like this. I am attempting to convert each element into its own array. I tried using lodash's chunk function but was unsuccessful. [ 'Product 1', 'Product 2', 'Product 3', 'Product ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Issues with Markdown text editor code, table, and list functionalities are causing malfunction

Looking for a solution to use markdown editor for writing blog posts? If you're facing issues with code blocks, list items, tables, etc., not working correctly after publishing your markdown-based posts, while other elements like images, links, and bo ...

Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows: [ { "info": "cute but big animal", "type": "pig", ...

Upon clicking a table row, generate a div underneath containing mapped data

My dynamic table is currently being filled with rows based on an array, but I want to display more data in an expanded view when a button in a row is clicked. However, I'm facing challenges as it seems I can't have two table rows within the same ...

Creating a jQuery alert similar to Stack Overflow's and integrating it with server-side functionality

I recently asked a question but unfortunately couldn't find the answer I was looking for. I came across this discussion on Stack Overflow about creating an alert box with dynamic data, but it wasn't exactly what I needed. After searching online ...

When the setDetached() function was called on an entity, it resulted in the removal of the getValidationErrors

When an entity is detached or not added to the manager, does the array of validations on the entity get destroyed? Will a newly created entity without being added to the manager lack the validation set on your model? This poses an issue for me as I am dy ...

The pagination feature in ng-table is not working as expected. Instead of displaying paginated table content

I am currently working on implementing pagination with ng-table, but I am facing an issue where all the data is being displayed on a single page instead of paginating it. Although there are no errors and the page numbers are shown, the content is not being ...

Issue with Ref when used in a distinct HTML template

I have encountered a frustrating issue with my simple Vue project. When I separate the template and code into individual files, the ref stops working and I end up with an undefined value in the HTML template. This scenario works fine: map.component.vue ...