What are the best strategies for mastering conditional promises in Angular?

I've been struggling with a problem in angularjs for several hours now.

Here's the pseudo code I'm working with:

doSomething(param){

    var res;
    if(param = "ok"){
        //perform some api calls with promises
        res = promise result
     }

    doSomeStuff(){
        //if res variable is set, continue here...
        // else
        //if res is not set, do something else...
    }

My question is: How can I achieve this functionality? The doSomeStuff function needs to be aware of whether the res variable has been set or not. It should either wait for it or proceed accordingly if not set.

Answer №1

To perform a single API call, you can utilize the then() method of the $http.

doTask(parameter){
    if(parameter === "ok"){
        //execute an API call with promise
        $http({
           method: 'GET',
           url: apiUrl
        }).then(
           function onSuccess(response) {
                processResponse(response);
           },
           function onError(response) {
              console.log(response);
           }
        );
    }      
}

When dealing with multiple API calls:

var doTask = function (parameter){
    if(parameter === "ok"){
       // Assuming listeUrl is an array containing URLs for API calls   
       var promises = [];
       for (var index in listeUrl ) {

          promises.push( //Add promises to an array
              $http({
                 method: 'GET',
                 url: listeUrl[index]
              }).then(function onSuccess(response) {
                 return response.data;
              })
          );
       }
       return $q.all(promises); // Wait for all promises to resolve before moving on to the next .then
    }      
}

doTask("ok").then(function(result){
    processResponse(result);
});

Answer №2

Implement the 'then' method in Angular to handle promise resolution and verify the data before executing any specific logic.

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

Refresh Google Maps without showing gray areas on the screen

Currently, I am utilizing the Google Maps API v3 in javascript and frequently reloading the map using an app.get while also incorporating layers and bookmarks via mongodb. Whenever I reload the map to erase everything, a gray background appears in the div ...

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

Activate a function upon the clicking of a button by utilizing a directive in Angular.js

In my directive, there is a function called "myFunction()", and in the template, I have a button. When the button is clicked, I want to execute the function without using ng-click for specific reasons. Instead, I am looking to assign a class to the button ...

Error: Unable to modify the div content - Uncaught TypeError: Unable to assign value to innerHTML of null

Attempting to update the contents of a div using JavaScript and innerHTML, but encountering an issue. After implementing the code to change the div's content, the functionality stopped working. The syntax has been double-checked. Tools being used in ...

Display the keyboard on IOS when an input field is selected

I'm facing an issue that seems to have no solution. When using input.focus() on IOS, the keyboard doesn't appear searchMobileToggle.addEventListener('click', function() { setTimeout(function(){ searchField.focus(); ...

"Troubleshooting: Resolving Compatibility Issues Between jQuery and XMLHttpRequest

I'm facing a situation with my website where the index.php page loads info.php through an AJAX call. The content from info.php is loaded using the following code: <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onready ...

Position the division at the location of the cursor for particular usemap components

Looking for a way to position a division on top of an image using a usemap. Interested in having the div only appear when the mouse hovers over a particular area, and at the precise location of the cursor. Came across some examples using jQuery, similar ...

Every time I try to run a basic thread code, it causes the Firefox extension (nsIThread

Whenever I try to create a basic thread in Firefox (Aurora 30), it consistently crashes. The only action it performs is executing the function "task" from the thread. Any thoughts on what could be causing this issue? function task(a, b) { alert(a ...

Adding to and retrieving data from an array

I am relatively new to the world of JavaScript and jQuery, and I have spent the last three days working on a script. Despite my efforts to find a solution by searching online, I have been unsuccessful so far. It seems like my search skills are lacking. My ...

Leverage external JavaScript to retrieve information from an XML file

I currently have a large amount of JavaScript code within my HTML file (1500 lines), and I am looking to relocate some portions of it to another JS file. My goal is to create a single file for importing data, and I am exploring the best approach to achieve ...

Is there a way for TypeScript to recognize that the potential data types in a union type align with the valid prototypes for a function? Any solutions available?

There seems to be an issue with this (playground link) code snippet: type ReplaceAll2ndArgType = string | ((substring: string, ...args: unknown[]) => string) export async function renderHTMLTemplate( args: Record<string, ReplaceAll2ndArgType> ...

Ways to transfer information from one view to another

I am working with a table that contains a details hyperlink. When the hyperlink is clicked, a new table is displayed on the same page in a different div. The hyperlink has 3 input parameters that trigger a service method to retrieve data. My current task i ...

Ensuring that objects remain fixed in place regardless of window resizing is a common task in web development, often achieved through a

I've been attempting to create range sliders with boxes that display the slider's current value, but I'm having trouble getting them positioned correctly when the window size changes. Despite trying various solutions found online, I resorted ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...

React - the perfect solution for managing dynamic inline styles

When it comes to handling inline styles, there are two scenarios to consider. Which approach is the most effective for 'toggling' CSS properties based on the component state - or is there a better alternative? 1. The first method involves creati ...

The ngModel feature is not functioning properly within the custom directive

After realizing my lack of understanding in AngularJs, I admitted that it was a challenge for me. Seeking clarity, I decided to post an example here and hope for assistance from someone knowledgeable on the topic. Thank you in advance. Html Part <test ...

Ways to halt the repetition of clicking the like button on my social media posts

I've been working on a new post system that allows users to like posts. Everything seems to be in order except for one issue - when iterating through the likes table from the post-like relation, the like button is being duplicated even with added cond ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

Is there a way to refresh a webpage on an express route and display an error message at the same time?

I'm currently in the process of building a basic website that includes features for user login and logout. This functionality is based on a local JSON file containing a list of users and their hashed passwords. My server setup involves using express s ...

The API endpoint does not include the Access-Control-Allow-Origin header on its resource

I have been attempting to utilize jQuery XHR to send a basic GET request to an API on Zillow. The response is visible in my browser and Postman, displaying correct results. Although I have redacted my API key below, the request itself could not be more str ...