Search code examples
javascriptangulartypescriptes6-promise

FileReader should complete onload function first then process further


I want to read the uploaded file and send those contents inside file via service API Call. But Onload function executes at last.I want onload function to be executed first then only move to further steps

checkInScript(file: File, scriptName: string): Observable<Response>{
    console.log("****Before Calling Method***");
    this.checkValidFile(file).then((value) => {
      console.log("****value****",value);
      this.fileValue.next(value);
    })
    console.log("****After Calling method***");
    const formData = new FormData();
    formData.append('updateScript', this.fileValue.value);
    console.log("****Form Data***");
    return this.http.post(this.mccScriptOperationURL  + '/updateScript/' + scriptName, formData);
  }

  checkValidFile(file: File): Promise<string>{
    const fileReader = new FileReader();
    fileReader.readAsText(file);
    return new Promise((resolve) => {
      fileReader.onload = () => {
        console.log("****Inside on Load*****");
        resolve(fileReader.result.toString());
      };
    });
  }

Current Execution pattern is : Before Calling Method* After Calling method* Form Data* Inside on Load* value

Required Execution Pattern is: Before Calling Method* Inside on Load* value* After Calling method* Form Data`


Solution

  • I was earlier going to suggest the same method as @JaromandaX but then realized the null problem that would create. I think awaiting the checkValidFile should work as expected, in the correct sequential order.

    async checkInScript(file: File, scriptName: string): Observable < Response > {
      console.log("****Before Calling Method***");
      const value = await this.checkValidFile(file);
    
      console.log("****value****", value);
      this.fileValue.next(value);
    
      console.log("****After Calling method***");
      const formData = new FormData();
      formData.append('updateScript', this.fileValue.value);
    
      console.log("****Form Data***");
      return this.http.post(this.mccScriptOperationURL + '/updateScript/' + scriptName, formData);
    }
    
    checkValidFile(file: File): Promise < string > {
      const fileReader = new FileReader();
      fileReader.readAsText(file);
    
      return new Promise((resolve) => {
        fileReader.onload = () => {
          console.log("****Inside on Load*****");
          resolve(fileReader.result.toString());
        };
      });
    }