How to implement a synchronous function to read a file?

Hi,
I have a function that posts a form that contains some mandatory text fields and an optional file.
This function should return an Observable.
When I have to send the file I have to read it before calling the web service.

I’m trying to write a synchronous function that reads the file, but, for now, the result is that the form is sent before the reading of the file is finished.

This is the function that sends the form:

  sendReport(values, fileObject = null) {
...
    console.log('formData: ', formData.getAll('data'));

    // If the file is passed the load it and add it to the formData
    if (fileObject && fileObject.filename) {
      console.log('ONE');
      const reVar = this.loadTempFile(fileObject);
      console.log('SIX');
      if (reVar) {
        formData.append('streamfile', this.tmpBlobFile, fileObject.filename);
      }
    }

    return this.httpClient.post(commandUrl,
      formData,
      {headers: headers, responseType: responseType});
  }

This is the function that reads the file:

  async loadTempFile(fileObject) {
    console.log('TWO');
    return await new Promise((resolve, reject) => {
      console.log('THREE --->', fileObject);
      this.file.readAsArrayBuffer(fileObject.directory, fileObject.filename)
        .then((res) => {
          console.log('FOUR');
          this.tmpBlobFile = new Blob([res], {type: fileObject.contentType});
          console.log('FIVE');
          console.log(this.tmpBlobFile);
          resolve(true);
        }, (err) => {
          reject(false);
        });
    });
  }

This is what I see in the Chrome console:

formData:  ["{"deviceId":80,"description":"gghh","warningTypeId":"2"}"]
main.js:3752 ONE
main.js:3767 TWO
main.js:3769 THREE ---> {data: null, uri: "file:///storage/emulated/0/Android/data/it.aaamobi…y.aaa/cache/IMG-20190406-WA0002.jpg?1559488047281", path:
...
main.js:3754 SIX
main.js:3772 FOUR
main.js:3774 FIVE
main.js:3775 Blob {size: 681660, type: "image/png"}size: 681660type: "image/png"__proto__: Blob

So loadTempFile returns before the file has been read
What am I doing wrong according to you?

Thank you very much

claudio

Admittedly, I find asynchronous programming confusing. But, I wonder if your problem is just that you need to await the call to loadTempFile().:

const reVar = await this.loadTempFile(fileObject);

Perhaps that will help…?

Hi,
if I write
const reVar = await this.loadTempFile(fileObject);

I have this error compiling the app:

Await expression is only allowed into an async function

However, I’ve followed this guide where await is not used calling the function but returning value in the function declared as async.

cld

Then, I’d recommend adding async to the function.