Ensure that the inner code has completed execution before moving on to the next iteration

My objective is to run a for loop 10 times in order to download a 3MB file from my server and record the time it takes (in ms). By repeating this process 10 times, I can then calculate the average download speed for the client.

However, I am facing an issue with the following loop:

$scope.startTest = function () {
    var dlTime = 0;
    for (var i = 0; i < 10; i++) {
        var wait = getLargeData();
        wait.then(function(result) {
            dlTime += result.dlTime;
            $scope.message += "\n finished loop " + i;
        });
    }
    $scope.message += "\n Total download time: " + dlTime;
}

The output of the above code snippet displays:

finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
finished loop 10
Total download time: 0

I understand that the issue lies in the asynchronous nature of the calls. How can I ensure that the loop waits for the .then call to complete before proceeding?

Edit: It is important to note that getLargeData() does return a promise

function getLargeData() {
    var loadTime = 0;
    var dlSpeed = 0;
    var promise = $q.defer();
    var startTime = new Date();
    $networkSvc.getLargeData()
        .success(function (data) {
            loadTime = new Date() - startTime;
            dlSpeed = 3 / (loadTime / 1000);
            var ret = { loadTime: loadTime, dlSpeed: dlSpeed };
            promise.resolve(ret);
            return promise.promise;
        })
        .error(function() {
            $scope.message = "Error - could not contact server.";
        });
    return promise.promise;
}

Answer №1

Utilize the $q.all method

    let promises = [promiseAlpha(), promiseBeta(), promiseGamma()];

$q.all(promises).then((values) => {
    console.log(values[0]); // value alpha
    console.log(values[1]); // value beta
    console.log(values[2]); // value gamma

    complete();
});

This function takes an array of promises and returns an array of completed promises. Here is more information on this topic.

The code you have written prints 10 ten times because those are promises waiting for data, while the variable 'i' gets incremented before the loop finishes. The $q.all method is used to resolve these ten promises. You can iterate within this context.

Answer №2

To optimize your code, make sure to utilize the Angular service called $q. Incorporate this into your existing getLargeData() function so that it returns a promise once executed. This will allow you to take advantage of its functionality by using getLargeData().then( .... For more information on how to implement this, visit the official documentation, where you can find helpful examples to get started.

Answer №3

There is no way around it.

  1. Eliminate asynchronous calls, which will result in your users experiencing delays (and you won't be able to download them simultaneously).
  2. Utilize Promise.all() (find out more here) or a similar promise implementation like $q. This enables you to execute a callback when all tasks are completed.

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

Can Jinja2 Be Utilized in JavaScript?

I've been grappling with this issue for quite some time now: {% for record in records %} var GPSlocation = "(37.7699298, -93.4469157)"; var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ") var Lat = parseFloat(LatLng[0]); var Lng = ...

Setting the Datetimepicker to be used with every input field

I currently have four textboxes identified by their unique ids: title, sdate, edate, and pdate. My goal is to assign a Datetimepicker to the textboxes that contain the word 'date' in their id. This means I want the Datetimepicker to be assigned ...

Check out the article on reading file uploads using jQuery or Javascript

I have a basic file upload field: <input type="file" id="signature" /> Here is the jQuery code I am using: $('#save').click(function() { var element = $('#signature'); if (element.files && element.file ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Is it possible for the state to be altered only when invoking an arrow function at an expo

I'm encountering an issue with the following function: const handleSave = (task, description, priorityState, taskID) => { changeLabel(task, taskID); changeDescription(description, taskID); changePriority(priorityState, taskID); navigation.g ...

What is the best way to track if a checkbox has been selected or not?

Working on a sports list for a mobile app using Ionic. There is a view where the user can select which sports they want to see on the list. <input type="checkbox" ng-model="sport.checked" ng-init="sport.checked=true"> After selecting ...

What's the reason for seeing "1:powershell" in the terminal when using react.js?

Can anyone explain why the terminal shows "1:powershell" in react.js? https://i.sstatic.net/1LyHe.png https://i.sstatic.net/5K95B.png ...

Issue encountered while attempting to write to csv-file using npm csv-writer - no error message displayed and function not working as

In my electron renderer.js process, I am attempting to write to a CSV file. Unfortunately, most of the time, the writing process doesn't work as expected, and the addition of .then is not executed. Despite this, no error messages or indications of mis ...

Using JSON with PHP to send data and receiving the response back with JavaScript

Despite exploring numerous questions and attempting various methods, I have been unable to find a solution that works. Here is my JavaScript file: function sendData() { var jsondata; var j = {"pub_id":"'+pid+'","a_type":"'+a_t&ap ...

Combining code to create a table and transfer files with the help of Rest API and Javascript

I have successfully implemented a code that draws a table using CEWP SPO. Now, I am looking to enhance this functionality by adding a button to each row in the table. This button should be able to move the corresponding files from their current location to ...

Tips for validating a string in a URL with Selenium IDE

When I click on a tab on my website, it triggers an AJAX service call where the URL contains parameters related to the data being loaded after the tab is clicked. The data is displayed as horizontal tiles one below the other, with 4 tiles being loaded pe ...

Unable to place a div within a nested div

Can you assist me in resolving an issue I am facing? I have the following code: <div id="div1"> <div id="edit1"> hello <input type="button" id="b1" onclick="aaa()"/> </div> </div> I am trying to insert ...

Initializing State for One Element While Neglecting the Other

Experiencing odd behavior in my React code. I assigned two elements to state one after the other, but only one of them is accurately represented in the state while the other is not. Both elements print properly before assignment. module.exports = React.cr ...

Exploring characteristics using DocumentTraversal

My goal is to list out the attributes of elements using DocumentTraversal specifically for IE11. While I have been successful in enumerating element attributes, I am facing an issue when trying to do the same with attributes. The enumeration stops at the f ...

attaching a CSS class to an element using an Angular directive

I need to implement a directive on an element that will have the following functions: 1. Add a click event to the element 2. Display a drop-down menu upon clicking To achieve the first function, I included a directive called "sortDirective" on my element ...

What is the most efficient method for converting a string into an object in a Node.js environment?

This code seems to be functioning correctly, but it appears quite lengthy. Is there a more concise approach to achieve the same result? The primary objective here is to extract a sorting parameter from an HTTP query and use it to sort a collection in Mong ...

The function button.click() is not compatible with Internet Explorer 11 and will not

I have implemented a jqx menu using the code snippet below: <ul style='width: 200px;'> <li onclick="logOffButton.click();">Sign off</li> </ul> My goal is to automatically trigger a click event on the "logOffButton" o ...

Updating Background Image with Create React App

Struggling with using Create React App to dynamically change a background image based on props passed to my component. The documentation recommends using the import syntax, but this would require hardcoding each image for every component. Is there a way to ...

Connect HTML and CSS files to your Meteor project

I need to incorporate a pre-existing lengthy form that includes both CSS and HTML files into my current meteor project. How can I achieve this? Is it possible to accomplish it in the following manner: <template name = "premadeForm"> somehow con ...

Is the functionality of defineProperty for elements malfunctioning on iOS6?

There seems to be an issue with JavaScript's defineProperty and __defineSetter not working on elements in iOS6. It functions correctly on all other browsers and earlier versions of iOS. Does anyone have more information on this? <input id='Bu ...