Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the web service.

However, I am encountering an issue where both resolves are being invoked.

I'm questioning whether or not I might be inadvertently utilizing a promise anti-pattern.

Below is the snippet of my code:

    function returnMapAsync() {

  return $q(function (resolve, reject) {
    if (navigationMap) {
      resolve(navigationMap);
    } else {
      ServerRequest.getNavigationMap().then(function (data) {
        navigationMap = data.object;
        resolve(navigationMap);
      });
    }
  });
}

Your guidance would be greatly appreciated. Thank you.

Answer №1

A common mistake is to think that everything must be enclosed in the $q() function call. To make navigationMap promise-friendly, try using $q.when:

function getMapPromise() {

    if (navigationMap) {
        return $q.when(navigationMap);
    }
    return ServerRequest.retrieveNavigationMap();
}

Answer №2

There is no need to add an extra layer of promise wrapping since ServerRequest.getNavigationMap() returns a promise:

function fetchNavMapAsync() {

    if (navigationMap) {
        return $q.resolve(navigationMap);
    } 

    return ServerRequest.getNavigationMap().then(function(data) {
        navigationMap = data.object;
        return navigationMap;
    });
}

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

What are the best practices for utilizing ngrx entity selectors?

Currently, I am utilizing ngrx entity for managing my store. However, I seem to be facing an issue with selecting the store entities using selectors. Despite following the code example provided in this link: https://github.com/angular-university/angular-ng ...

Achieving an isolated scope in AngularJS while setting parent values through ajax

I've been working on creating a reusable directive for a form, and things were going smoothly until I needed to pass a callback function from an attribute to my http factory. In order to do this, I had to change the 'scope' in my directive o ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

Custom Angular directive for toggling button state during AJAX requests

I have an application with a form that has a save button. After submitting the form, a function save() is triggered to make an ajax request for form submission. Is there a way to create a directive that changes the text on the button from "Save" to "Loadin ...

Validating the userid with jQuery before form submission

Currently, I am working on a form where I need to validate if the userID is already in use before allowing the user to submit it. After some research, I came across a solution on another website. However, when I tried to implement the code, I encountered ...

Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example: [ { "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222", "AnswerOptionIds": [ "76e32546-0e26-4037-b253-823b21f6eefb", "10d02a3e-9f9f- ...

Effortlessly browse through directory with the seamless integration of AngularJS or

Hey there! I'm working on a really cool feature - creating a list with editable inputs. However, I've encountered a bit of an issue. Is there any way to navigate through this list using arrow keys and focus on the desired input? .content ul { ...

Encounter the following issue: Unable to access property '0' due to being undefined

After restructuring my entire Javascript code, I managed to solve the problem with asynchronous calls. However, an error occurs when editing a repair and the server prompts the client for repair information again. The error message displayed is "Uncaught ...

How to update a <table> in AngularJS or JavaScript to keep it current

I've been trying for hours to figure out how to refresh the <table> with random values when a button is clicked. I've assigned id="myTable" to the <table> and tried using the .reload() function, but it's not working. Any suggesti ...

Error: The module '/@modules/vue.js' does not export a 'default' value as requested by the syntax

I'm encountering an issue with Vee Validate form validation in Vue.js. As a beginner, I am struggling to grasp the import syntax. After installing vee-validate using npm i vee-validate --save and placing it in my node_modules directory, I proceeded to ...

Implementing server-side middleware for individual routes in Next.js

I am currently exploring options for executing code upon the initial page load of each request. My goal is to determine the domain of the request and redirect to a specific section of the website based on this information. One possibility I have considere ...

Combine various choices into a select dropdown

I am facing an issue with an ajax call in codeigniter where the response always consists of two values: team_id1 and team_id2. Instead of displaying them as separate values like value="1" and value="2", I want to join them together as value="1:2". I have ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...

Incorporate Live Data into Google Charts Using Ajax Response for a Dynamic Visualization

I am struggling to successfully load a responsive Google Line Chart after an Ajax call. I have attempted to place the entire Google Chart code within the success part of the Ajax call, but it does not seem to work as expected. Below is my current Ajax code ...

Tips for adjusting the starting day of the date picker in AngularJS ui-bootstrap

Does anyone know how to customize the starting day for the ui-bootstrap date picker in AngularJS? Currently, the days are displayed from Monday to Sunday, but I need them to start from Saturday and end on Friday. Check out this plunker <p class="inpu ...

Error Alert: jQuery AJAX Event is not defined in Firefox Browser

This snippet works perfectly on Webkit browsers, but for some reason, it's not functioning in Firefox. I have a feeling that I need to include "event" within parentheses somewhere, but I'm unsure about the correct placement. Any ideas? html < ...

Exploring the Power of ReactJS Source Mapping

After adding the .env file to my react project, I noticed that when the project is uploaded to the server, the console source is displaying all components. Although I added the .env file and included the following code: GENERATE_SOURCEMAP = false; The i ...

Inconsistencies in date formatting between Javascript and PHP yield varying results

While working with PHP, I noticed this: echo date("Y/m/d",786668400); The output is 1994/12/06 However, when I tried the same thing in JavaScript: console.log(new Date(786668400*1000).getDate() + "." + (new Date(786668400*1000).getMonth() + ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

What is the process for adjusting the form transition?

I am currently working on a form that has a transition effect However, I encountered an issue: check out the problem here My goal is to keep the magnifying glass fixed in place while the form moves Here is a snippet of my code: import Search fro ...