What is the best way to create a series of synchronous HTTP requests using $http in AngularJS?

I am facing the challenge of uploading a list of video objects with different attributes and links. Currently, I have set up a loop to go through each object in the list and upload the videos one by one since the service I am using does not support multiple uploads simultaneously. This means that I need to wait for the first video to finish uploading before moving on to the second, and so on.

Below is the code snippet handling this process:

$scope.upload = function(){
    $scope.videoList.forEach(function(video){
        video.state = "Downloading"
        $scope.msg = "The video is downloading"
    $http.post("/download",{link : video.link,title : video.title}).then(function(resp){
      $scope.msg = "The video has been downloaded on the server, it will now start uploading"
      var filen = resp.data["fn"]
      var title = resp.data["title"]
        video.state = "Uploading"
      $http.get("/uploadVid?file=" + filen +"&title=" + title).then(function(resp){
        if (resp.data == "0002"){
        alert( "You didn't authorize the App yet, please authorize it to be able to use it .")
      }
      if (resp.data == "000X"){
        alert("An error occured, please retry .")
      }
      else{
        $scope.msg = "the video uploaded, here's the link: " + resp.data
        video.state = "Done"
        video.link = resp.data
      }
      } )
    })

    }) }

The issue at hand is that even though the videos should ideally be downloaded and uploaded sequentially, due to the asynchronous nature of the $http calls, all downloads and uploads occur simultaneously. The loop progresses without waiting for the current iteration to complete, leading to undesired simultaneous actions. I am looking to make this synchronous, where each video is processed one after the other. Ideally, I would prefer not to implement the Promises Interface as I am pressed for time and lack familiarity with it. However, if you are well-versed in Promises, your insights and explanations would be greatly appreciated.

Answer №1

Avoid making the requests synchronous; instead, aim for a sequential approach. A synchronous ajax request can block the JavaScript UI thread and create a poor user experience. Performing them sequentially means carrying out one after the other in sequence rather than simultaneously.

One common method is to keep track of your progress, process each request, and then move on to the next one as shown below:

$scope.upload = function() {
    var videos = $scope.videoList;
    var index = 0;
    if (videos.length) {
        next();
    }

    function next() {
        var video = videos[index];
        video.state = "Downloading";
        $scope.msg = "The video is downloading";

        $http.post("/download", {
            link: video.link,
            title: video.title
        }).then(function(resp) {
            $scope.msg = "The video has been downloaded on the server, it will now start uploading";
            var filen = resp.data["fn"];
            var title = resp.data["title"];
            video.state = "Uploading";

            $http.get("/uploadVid?file=" + filen + "&title=" + title).then(function(resp) {
                if (resp.data == "0002") {
                    alert("You didn't authorize the App yet, please authorize it to be able to use it .");
                }
                if (resp.data == "000X") {
                    alert("An error occurred, please retry .");
                } else {
                    $scope.msg = "the video uploaded, here's the link: " + resp.data;
                    video.state = "Done";
                    video.link = resp.data;

                    if (++index < videos.length) {
                        next();
                    }
                }
            });
        });
    }
}

Please note that this example may lack some details, but the main concept should be clear.

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

Updating a field in Mongoose by referencing an item from another field that is an array

I have developed an innovative Expense Tracker Application, where users can conveniently manage their expenses through a User Collection containing fields such as Name, Amount, Expenses Array, Incomes Array, and more. The application's database is p ...

What method is best for deleting an item from the database in HTML structure - POST, GET, or XHR action?

I have a webpage that displays content in a table format and allows users to delete a specific row by clicking on it. The structure of my rows is as follows: foreach ($rewards as $reward) { echo '<tr id="' . $reward[&apos ...

Unexpected error occurs when modifying HTML5 video source using JQuery on Internet Explorer

Currently, I am working on developing a web application using asp.net, Bootstrap, and JQuery. While testing it on LocalHost, I encountered an issue that needs debugging. The navigation bar of my application has a dropdown menu with links to tutorial video ...

Tutorial on inserting a picture into muidatatables

Important Note: The image stored in the database is called "profileImage." I am looking to create a dynamic image object similar to other objects. When I input this code: { label: "Image", name: "profileImage" }, it simply displays the image endpoint as ...

Guide to altering the color of the row that is clicked in a table using css and jquery

Is there a way to change the text color of a row in a table when it is clicked, similar to an example like this but without changing the background color? The code I have tried is not working for me. Below is a snippet of the code I am using: $("#myTab ...

Differences between React's useCallback and useMemo when handling JSX components

I have created a custom component called CardList: function CardList({ data = [], isLoading = false, ListHeaderComponent, ListEmptyComponent, ...props }) { const keyExtractor = useCallback(({ id }) => id, []); const renderItem = useCallba ...

Swap out a paragraph with a city name fetched from a JSON file

While working on a weather app, I encountered an issue. The app needs to automatically detect the user's location and display the appropriate temperature along with the city name. I have been trying to fetch data from JSON to replace the placeholder t ...

Using TypeScript to retrieve a strongly typed promiseValue from an angular $modalInstanceA

New to TypeScript Question: I'm working on returning a strongly typed promise from angular's $modalInstance. Here is an example of what I have: this.$modal.open(options).result.then(result => { At the moment, 'result' is of typ ...

What are the benefits of having a service dedicated to interacting with a single entity, while another service is responsible for handling a group of entities?

Imagine we have a User entity. Would it be better to have two smaller services (User and Users) or one larger service that manages both individual Users and collections of Users? If it's the latter, what's the recommended practice for naming the ...

Error Encountered When Trying to Import BrowserAnimationsModule in Angular 5: Unexpected Token "<"

As I try to integrate the BrowserAnimationModule into my Angular 5 project, a rather foolish error keeps popping up. Error: (SystemJS) Unexpected token < SyntaxError: Unexpected token < at eval (<anonymous>) at Object.eval ...

I want to create a custom jQuery slider totally from scratch

Greetings everyone, I have been tasked with creating a slider using only HTML / jQuery code. Here is the template: And here is the HTML code for the template above: <div id="viewport-container"> <section id="sliding-container"> & ...

The JavaScript function is designed to only accept whole numbers as input

Whenever I invoke a JavaScript function and pass along 4 parameters, it only functions properly if the fourth parameter consists of integers exclusively. Below is the code snippet for my onchange function: onchange="weekchange(this, <?php echo $i ?> ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

AngularJS synchronous $resource functionality allows for the ability to make parallel API

I'm facing a dilemma because I understand that Javascript isn't designed for synchronous work, especially in the case of AngularJS. However, I find myself in a situation where I require it. The main page on the "www" domain (built with AngularJS ...

Troubleshooting Cordova's ng-route functionality issue

I am currently working on an Angular application that includes the following code: // app.js var rippleApp = angular.module('rippleApp', ['ngRoute', 'ngAnimate', 'ngAria', 'ngMaterial']); // configure ou ...

Using Golang to encode JSON for parsing in JavaScript

I am working with a struct that looks like this: type User struct { Login string `json:",string"` PasswordNonce Nonce `json:",string"` PasswordHash HashValue `json:",string"` CreatedOn time.Time `json:",string"` Email ...

json array: Tips for adding elements to a new array

In order to achieve my goal, I am looking to create a JSON array structure similar to the one shown below: var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}]; How can I modify the code snippet provided below to generat ...

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. < ...

Activation of navigation buttons in the Vue Full Calendar control the movement to the next and previous

In my current project, I am utilizing https://www.npmjs.com/package/vue-full-calendar. However, I have encountered an issue when trying to receive callbacks or triggers from the next and previous buttons on the calendar. My backend API is structured aroun ...

Submitting form data triggers an AJAX request that retrieves and displays the desired content within a

When it comes to opening search results in a specific form on a webpage using Ajax, many developers may face certain challenges. Here is an example of how it can be implemented: <form id="searchForm" method="GET" > <INPUT TYPE="text" N ...