Functions return value but array length are returning 0

Hi,

I created 2 functions for multiple file uploads where I need to get the ID of the file after the file upload then save the id into array and process it later on, but the data returned the value but array length always show 0.

   upload() {

    const files = this.fileField.getFiles();
    const formData = new FormData();

    return new Promise( (resolve, reject) => {
      return this.storage.get('authtoken').then((authkey) => {
        files.forEach((file) => {
          formData.append('files[]', file.rawFile, file.name);
          this.http.post(
            this.authService.AUTH_SERVER_LIVE + '/file/upload', file.rawFile, {
              headers: {
                'Content-Disposition': 'file; filename="' + file.name + '"',
                Authorization: 'Bearer ' + authkey,
                'Content-Type': 'application/octet-stream' }})
            .pipe(catchError(e => this.handleError(e))).subscribe((filesData: any) => {
              console.log('files uploaded', filesData);
              this.fileFids.push({id: filesData.fid[0].value});
            });
        });
        resolve(this.fileFids);
      });
    });

  }

and I run it using this code :

   async runcode() {
    await this.upload().then((fids: any) => {
      console.log('uploaded:', fids);
      console.log(Array.isArray(fids));
      console.log(Object.keys(fids).length);
      this.callanother(fids);
    });
  }

but the results are showing, but the array length are always returned 0 even though I can see the length in console is not 0.

and also the console in the runcode() function shows 1st before the console log in the upload code :

uploaded: []0: {id: 3377}id: 3377__proto__: Object1: {id: 3378}length: 2__proto__: Array(0)
form.page.ts:109 true
form.page.ts:110 0
form.page.ts:336 files uploaded {id: Array(1)]__proto__: Object
form.page.ts:336 files uploaded {id: Array(1)]__proto__: Object

is there anything that I am missing?

You have to check the API end first. How the API is returning the data.

Or you can try with Content-Type: application/json

server is returning the data, its not with the content type issues

Try rewriting this so that:

  • every parameter and return type of each function has a declared type (not any);
  • the keyword new does not appear;
  • you never modify any external state (which disqualifies what you are doing with this.fileFids) - no writing to any properties of this;
  • the first word of any function returning a future (Promise or Observable) must be return

These rules may seem arbitrary, but I have found them relentlessly effective in stripping away bugs of the type you seem to have here.

What you return currently is the result of return this.storage.get(...), the resolve(...) does not return anything. resolve only resolves the inner promise, not the outer one that you’re accessing from upload.then()

Try rather return Promise.resolve(this.fileFids); so the return from the inner callback is reflected on the outer promise

But that won’t be enough to solve the issue. More problematic than that is that in your code, the synchronous resolve(...) will be executed before the forEach(...) ends as it contains asynchronous (non-blocking) code. So make sure to run resolve()upon completion of inside promises/observables. Currently it is executed before.

I am new with promises so to be honest, I dont quite understand the methodlogy yet :frowning:

hmm let me try implementing it again

the funny thing is the result are being spit out in console.log, I assume its not finished being processed yet?

okay after banging my head around and discussion with my friend, we came up with the best solution for it is to use multipleresponse method where we did the :

requestDataFromMultipleSources(files, authkey): Observable<any[]> {
return forkJoin(multipleResponse);
}

this solve my issues!