Execute the same asynchronous function multiple times using promises

I have created an async function that looks like this:

$scope.obtain_device_version = function(){
       return $q(function(resolve, reject){
            $http.get('/api/retrieve_version')
                .then(function(response) {
                    resolve(response.data.version);
                },function(response) {
                    reject("Connection lost..");
            });
       });
};

Query 1: How can I execute this function consecutively 10 times in a row?

Query 2: Is there a way to keep running the function until a specific response is received from the http-request?

Answer №1

Examining Question 1

.then(callback) will generate a fresh promise that resolves to the output of callback, or if the result is another promise, it will resolve to that promise's value once settled. This technique is useful for sequencing asynchronous operations. For instance, in this scenario:

function myFunction() { return promise; }

the code snippet below will execute myFunction consecutively 10 times

var result = $q.resolve();
for (var i = 0; i < 10; ++i) {
    result = result.then(myFunction);
}
result.then(function () { /* myFunction has been executed 10 times */ })

Inquiry Question 2

In this case, recursion becomes necessary as the exact number of iterations is unknown. When dealing with a similar myFunction setup as previously mentioned:

function wrapper() {
    var deferred = $q.defer();

    iter();
    function iter(res) {
        // Skip first iter() call, and wait for acceptable res
        if (result !== void 0 && /* res meets criteria */) {
            return deferred.resolve(res);
        }

        // Recursive call
        return myFunction().then(iter);
    }

    return deferred.promise;
}

wrapper().then(function (res) { /* res meets criteria */ })

Note that in such scenarios, promises may not necessarily provide an advantage over traditional callbacks.

Answer №2

Question 1:

var request = null;

for( var count = 0; count < 10; count++ ) {

  if( request )
      request.then( $scope.get_device_version );
  else
      request = $scope.get_device_version();


}

Question 2:

$scope.get_device_version = function(){
       return $q(function(resolve, reject){
            $http.get('/api/get_version')
                .then(function(response) {

                    if( /*Not the correct version? run again:*/ )
                        $scope.get_device_version()
                    else
                        resolve(response.data.version);


                },function(response) {
                    reject("Connection lost..");
            });
       });
};

Answer №3

This code is simulated and has not been validated through testing.

var verifyDeviceVersion=function (attempts) {
    $scope.fetch_device_version().then(function(data) {
        if(attempts==0) return;
        verifyDeviceVersion(attempts-1);
    });
}

var continueVerification=function () {
    $scope.fetch_device_version().then(function(data) {
        if(data.valid_condition) return;
        continueVerification();
    });
}

To initiate, use verifyDeviceVersion(10) or continueVerification()

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

Best Practices for Naming Logout Endpoints in REST APIs

As someone who is just starting out with coding, I have a question about naming conventions for routes. When creating a route for adding a new user, I typically use something like this: router.post("/users", async (req, res) => {} And for l ...

Discovering the correct element and typing for an HTML attribute through JavaScript

We are currently working on test automation and I am looking for a way to identify the Element and Type associated with it within an html (Data-qa) attribute. For example, when looping through, the Element is identified as input and the type is radio. < ...

Set checkbox variable to undefined at all times

I am having trouble determining the state (True/False/null, etc.) of my "CSS-only" toggle switch. No matter what I try, I keep getting a null value. I'm not sure why this is happening, but it seems that the checkbox input is not functioning as expecte ...

Adjusting the color of a value in justGage requires a few simple steps to

Is it possible to modify the color and design of the text in the Value parameter of justGage after creating the gauge? My goal is to change the text color to blue with an underline to give it a link-like appearance. Appreciate your assistance. ...

The Ajax request is only sending the ID of the initial element

I'm having an issue with dynamic links that all use the same < a > tag. When I click on these links, my AJAX call loads the content correctly, but the new div only shows the id of the first link when other links are clicked. To see the id in the ...

The error message "TypeError: 'undefined' is not an object ('_this.props')" indicates that the property '_this

Having trouble solving this issue. Need assistance with evaluating 'this.props.speciesSelection.modalize' <BarcodeInput speciesSelection={this.props.speciesSelection} species={species[0]} barcode={{ manufacturerValue: ...

Retrieving information from a datatable in vb.net with an array

Working on a chart using highcharts with code behind in vb.net... I have a datatable structured like this: Date - speed - data 2011 10k 6 2011 18k 7 2012 20k 10 2012 10k 2 2013 14k 4 2013 20k 6 Previously, to ...

What steps should I take to make the initiallyHidden attribute in FusionCharts work properly?

I am encountering an issue with my chart that is reloaded periodically. I want to make sure that the series hidden by the user (by clicking on their legend names) remain hidden even after reloading. I attempted to set the series initiallyHidden attribute t ...

How does Python interpret arrays from JavaScript?

As part of my API setup, I am sending parameters to a python script. One of these parameters happens to be a JavaScript array. Interestingly, when I check the array in Python, it only shows the first index. Here is the snippet of my Angular JS get request ...

Increase initial zoom for React Three Fiber OrbitControls to provide a wider view

I've been working on a project in React Three Fiber using this codesandbox for practice. My query regarding the demo is about setting a wider initial zoom in OrbitControls to view more small stars. Can anyone help with this? Below is the code snippe ...

Encountering Issues with Laravel AJAX POST Request (500 Internal Server Error)

I have been struggling with this issue for hours, going through numerous examples and StackOverflow answers without any success. This is my first time working with AJAX, although I do have considerable experience with Laravel. The problem I am facing is a ...

Perplexing behavior displayed by non-capturing group in JavaScript regular expressions

Here's a straightforward question for you. Regex can sometimes get tricky, so thank goodness for simplifying things... In the URL, there's a query parameter labeled ?id=0061ecp6cf0q. I want to match it and only retrieve the part after the equal ...

Using Angular JS to redirect to a CodeIgniter controller involves utilizing the routing capabilities of Angular

Currently, I am implementing CodeIgniter controller functions (example). <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Me extends CI_Controller { public function __construct() { ...

Utilize JavaScript to Forward Subdomain to Main Domain

Utilizing Apache envvars, I have created the MYDOMAIN and MYSUBDOMAIN variables to define 'mydomain.com' and 'sub.mydomain.com'. These variables are then used in the Apache sites-available conf files for website deployment. The 'su ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Issue: An error was encountered during the hydration process. Since this error occurred beyond the Suspense boundary, the root element will now transition to client rendering

I've encountered the same error every time while developing a website with Next.js. Unable to pinpoint the issue in my code. const Login = () => { const [userMsg, setUserMsg] = useState(""); const [email, setEmail] = useState("& ...

Printing the HTML Template of a widget with multiple loops results in a blank first page being displayed

I have encountered an issue while working with a table and ng-repeat loops in my report widget. The table displays fine on the screen, but when I try to print it, there is always a blank page at the beginning. Interestingly, if I remove the second and thir ...

Issue with PHP form submission not functioning within a table when utilizing jQuery

I've created a function that retrieves user data. function returnChild(){ global $pdo; $stmt = $pdo->prepare("SELECT * FROM children INNER JOIN districts ON children.ch_district = districts.dst_id ...

What is the best way to prioritize the display of custom login buttons based on the last button used for login?

I have implemented 4 different login methods for my app, each with its own associated component. I am looking to rearrange the buttons based on the last used login method. I already have a function to determine the last login method. let lastSignedInMetho ...

Creating a custom script for a search field that retrieves information from an XML document

Attempting to create a script that iterates through an XML file, the provided code currently displays alerts but fails to show information when a valid value is entered into the search field. However, upon removing the error checks and keeping the final ...