angularjs running multiple promises sequentially with $q

I was recently tackling a project in AngularJS 1.5.3, and I've run into some difficulties with chaining promises.

Here's a snippet of the function causing me trouble:

this.login = function(username, password) {
    var promise = $auth.login(username, password).then(...); 
    return promise;
}
this.tests = [
    ['I am the LoginController, responsible for user login'],
    ['I have a logs attribute to bind the current state to the view', null, function() { return !!angular.isArray(self.log); }],
    ['I make use of the $auth attribute to expose the $auth service', function() { return !!(self.$auth === $auth); }],
    ['I can retrieve tokens from the server', null, function() { return self.login({username: 'example', password: '1234'}); }, function() { return !!($auth.currentUser.id === 1 && $auth.currentUser.hasValidToken() === true); }]
];

You can probably grasp my intentions here...

The array structure is as follows:

[
    0 => string,
    1 => a function that returns a promise,
    2 => a function that verifies the impact of the preceding function
]

I had the idea of building a directive to automatically test controllers with visual cues - regardless -

What I require is to iterate through the array, execute them sequentially, and return true/false based on [1,2];

Initially, I tried directly within an Angular1 template using ngRepeat

<ul>
  <li ng-if="$last" ng-repeat="test in tests">{{test[0]}} :: {{test[1]() && test[2]()}}</li>
</ul>

This approach failed miserably since they weren't executed in order. It dawned on me that I needed to wrap them in promises?

Answer №1

To ensure all tests in a controller are executed before displaying them using ng-repeat, you can leverage $q.all(). This allows you to store the results of each test in a separate variable. Here's an example approach:

var testCases = [
    ['Testing LoginController for user login functionality'],
    ['Checking for logs...', null, function(){return !!angular.isArray(self.log)}],
];

var promises = [];

scope.testResults = [];
scope.testsExecuted = false;

for (var i = 0; i < this.pendingScenarios.length; i++) {
    var testCase = this.testCases[i];
    if (testCase[1]) {
        var result = $.when(testCase[1]());
        result.then(function(result) {
            testResults[i] = result;
        });
        promises.push(result);
    }
    // ...
}

$q.all(promises).then(function() {
    $scope.testsExecuted = true;
});

This code hasn't been tested yet, but it demonstrates the concept. If a test returns a Promise, add it to an array and ensure that all Promises are resolved using result.then().

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

The distortion of Blender animation becomes apparent once it is imported into three.js

I've been working on a project where I'm incorporating animations into a scene using a combination of blender and three.js. It took me several hours of trial and error to finally get the model and animation successfully imported into three.js. I ...

Substituting Div containers with elements imported from external files

Imagine I have <div> <div id="stuff"> <!-- stuff --> </div> </div> Could I move the content of <div id="stuff"> into a separate file named stuff.html, and then replace the code above with something simi ...

Is there a way to merge arrays in jQuery by pushing one array into another?

I am looking to construct an array as shown below. var coordinates = [ [41.02178, 29.26108], [41.02196, 29.26067], [41.02251, 29.26031], [41.02258, 29.26015], [41.02267, 29.25926] ]; My attempt in the code was as follows: var locations = []; f ...

What is causing the react-jss style functions to not run when the mobx store is updated?

I am currently utilizing mobx-react in conjunction with the react-jss library for styling purposes. However, I am encountering an issue where the updates to the store do not trigger the functions within the style definition to execute with the new props. T ...

What causes the empty gap to appear during animated transitions between two 'div' elements?

Is there a way to eliminate the white space in between elements during animation? Should I wrap both divs into another div to achieve this? I am using position-top to adjust my div animations. Could this be causing the issue? What other methods can you s ...

Automatically append a version number to destination output files using the Grunt task runner

We have a package.json file that contains our version number, like this: { name: "myproject" version: "2.0" } The objective is to dynamically insert the version number from the package.json file into the output files. Instead of manually updating ...

Responding to a tweet with the help of twit and Node.js

Utilizing the Twit Node.js API has presented me with a challenge. I am attempting to reply to a tweet that contains a specific keyword. My goal is for my response tweet to appear nested underneath the original tweet, much like how replies function on socia ...

Tips for receiving an ajax response in Vue.js 2

Here is the code snippet I am working with: <template> <a href="javascript:" class="btn btn-block btn-success" @click="addFavoriteStore($event)"> <span class="fa fa-heart"></span>&nbsp;Favorite </a> &l ...

Rearrange the position of the package.json file to the parent directory within the react application

Recently, I began learning React and used npx create-react-app frontend to set up my React app. This gave me the following directory structure: -- demo -- frontend -- node_modules -- public -- src -- .gitignore - ...

Next.js experiencing development server compile errors and broken page routing in production builds

Howdy everyone! I'm currently working on an app using Next.js. Every time I make a change, the server automatically compiles with the updates, but unfortunately, the pages often fail to render properly. Sometimes it takes several minutes for them to l ...

What is the proper way to display the initial content of the menu?

I am currently working on a website design for an upcoming festival. The festival spans over three days, so I have created buttons to navigate and load the content for each day separately. Is there a way for me to make the content for the first day di ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

Fundamental Guidelines for Firebase

I've recently started working with Firebase and I'm encountering some issues with the security rules. My project is a blog website where visitors can read posts, users, and comments without being logged in. However, logged-in and verified users ...

Navigating routes with regular expressions in Express

Recently, I've implemented the regex pattern /^\/(\d{5})$/ in my express route. However, an error has surfaced. The error message reads: SyntaxError: Invalid regular expression: /^\/^\/(?(?:([^\/]+?)){5})$\/?$/: Inval ...

Trying to figure out how to execute a codeigniter helper function with JQuery AJAX?

I created a handy function in my helper file within codeigniter that formats prices based on the value and currency ID provided. if(!function_exists('format_price')){ function format_price($val,$curency_id=NULL){ $CI ...

What is the best way to continuously loop the animation in my SVG scene?

After designing a SVG landscape with an animation triggered by clicking the sun, I encountered an issue where the animation only works once. Subsequent clicks do not result in any animation. Below is my current JavaScript code: const sun = document.getEle ...

Error encountered in React Material UI: Appbar - TypeError occurred when attempting to read properties that are undefined (specifically, reading '100')

Currently, I am working on developing a multi-step form using Material UI components. However, upon importing the necessary components, an error is being displayed in my code snippet: import React from 'react'; import { ThemeProvider } from &a ...

PHP code for sending email with attachment file

I have created an HTML form with the option to upload a file and send it to me via email. Additionally, I already have a PHP script that sends textbox values and text area values via email. Now, I would like the uploaded file from the form to be sent to m ...

The form will be submitted even if the validation conditions are not met, and the form

I've been struggling to understand why this issue keeps occurring despite hours of unsuccessful research. Here's the code for a registration page that submits the form regardless of the conditions being true or false. I've experimented with ...

Transform React.js data from MySql into a variable

Hello there! I encountered an issue while working on coding my web app. **I am looking to execute this class only if the "swishes" value retrieved from a table in my MySQL database is greater than 0.** var thepos = 1; export default class W ...