Make sequential http requests in Angular

Some days ago I ran into a problem: I had a list of n files that had to be uploaded to the server. If I had used a for loop to post my client attachments, I would have opened too many connections. So that it was necessary to limit the uploading process to one file at time. In order to do that, I resorted to recursion.

Immaginate to have a list of files and a method used to add a new file to the list. When the user presses on the add new file button, the client converts the files content to Base64, wrapps the obtained string into an object and adds it to the files array.

export class FileUploaderComponent implements OnInit {

  files: Array<File>;

    this.files = [];

   addFileToArray(file: File){

After that, when the user presses on the submit button, the client should call recursively an upload method starting from the first file of the list. Thus in the same class we should add also two new important methods: submitButtonClicked() and uploadRecursively().

   if (this.files.length > 0){
   this.uploadRecursively(0, () => {/*callback function - do something*/});

As you ca see, the submitButtonClicked() calls the uploadRecursively() method, passing to it the first position of the file to upload and a callback function which is useful to do something after we finished to upload all files in the array. Our uploadRecursively() implementation is the following:

uploadRecursively(n: number, callback: any) {<File>('http://localhost:8081/test', this.files[n]).subscribe(data => {
      if (n < this.files.length - 1) {
        this.uploadRecursively(n + 1, func);
      } else {

We can notice that uploadRecursively() will be called every time the previous call ended with success and our variable n is not greater than the array length.