resolved after a new promise returned nothing (console.log will output undefined)

Here is my Promise Function that iterates through each blob in Azure BlobStorage and reads each blob. The console.log(download) displays the values as JSON.

However, when trying to close the new Promise function, I want the resolve function to return the JSON data from reading the blobstream. In my case, resolve does not lead to anything.

The code in Angular Service.ts file looks like this:

getData(): Promise<JsonData[]> {

    return new Promise(async resolve => {

      const containerName = "blobcontainer";
      const containerClient = this.blobServiceClient.getContainerClient(containerName);

      //list blobs
      let i = 1;

      async function main() {
        i = 1;
        for await (const blob of containerClient.listBlobsFlat()) {

          console.log(`Blob ${i++}: ${blob.name}`);
          const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
          //console.log(blockBlobClient)
          const downloadBlockBlobResponse = await blockBlobClient.download(0);
          const download = await blobToString(await downloadBlockBlobResponse.blobBody)
          //console.log(downloadBlockBlobResponse)
          console.log(download)

        }

      }

      async function blobToString(blob: Blob): Promise<string> {
        const fileReader = new FileReader();
        return new Promise((resolve, reject) => {
          fileReader.onloadend = (ev: any) => {
            JSON.parse(ev.target!.result)
            resolve(JSON.parse(ev.target!.result));
          };
          fileReader.onerror = reject;
          fileReader.readAsText(blob);
        });
      }
      const _blob = await main().catch((err) => {
        console.error('message'); return null
      });

      resolve(_blob)  //resolve should return downloaded JSON file, but it didn't


    })
  }

Then in the component file, I intend to retrieve the data from the resolve function, which should return JSON string variables like "name", "timestamp", "value". However, in my case, I receive metadata from the blob instead of the contents. This indicates that the service.ts file is not correctly programmed:

xy.component.ts

export class xyComponent implements OnInit {
  @Input() title: string;
  jsondata: JsonData;
  name: String;
  timestamp: string;
  value: number;

  private jsonlistService: JsonDataService;
  jsondatas: JsonData[]=null;

  constructor(private jsonService: JsonDataService) {
    this.jsonlistService = jsonService;
  }

  ngOnInit(): void {

    this.jsonlistService.getData()
      .then(results => this.jsondatas = results);

      console.log(this.jsonService)

  } 
}

EDIT: Even if I return download at the main function, the resolve from main() still does not deliver the json string.

Second EDIT: Here are some snippets on how to return data:

async function main() {
        i = 1;
        for await (const blob of containerClient.listBlobsFlat()) {

          console.log(`Blob ${i++}: ${blob.name}`);
          const blockBlobClient = containerClient.getBlockBlobClient(blob.name);
          //console.log(blockBlobClient)
          const downloadBlockBlobResponse = await blockBlobClient.download(0);
          const download = await blobToString(await downloadBlockBlobResponse.blobBody)
          
          //console.log(downloadBlockBlobResponse)
          console.log(download)
          return download
        }

      }

But I am still unable to receive the downloaded file. The error persists. Any help would be greatly appreciated.

Answer №1

Ensure you are returning the result from main. Don't forget to return the final output.

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

Setting a Validator for a custom form control in Angular: A step-by-step guide

I need to apply validators to a specific control in formGroup from outside of a custom control component: <form [formGroup]="fg"> <custom-control formControlName="custom"> </custom-control> </form> this. ...

Displaying JSON data dynamically by iterating through it in a loop

While working with JSON data in a loop, I noticed that the code quality does not meet my expectations. I have a feeling that I might be missing something in my approach. $(function(){ $.getJSON('data.json', function(data){ let content ...

Create a fresh trail underneath the overlay image

When utilizing fabric.js to draw a new path with isDrawingMode: true enabled (seen on the right side of the screenshot), I am encountering an issue where the path appears above my overlay image, which is a transparent png. https://i.stack.imgur.com/R3fGn. ...

Obtain a custom token after next authentication through Google login

Utilizing next js, next auth, and a custom backend (flask), I have set up an API Endpoint secured with jwt token. In my next js frontend, I aim to retrieve this jwt token using the useSession hook to send requests to these API Endpoints. Everything functio ...

Issue with displaying Angular index.html page post-build

My Angular application runs smoothly on ng serve, but after building and uploading with ng build --prod, the index.html file fails to open. I've tried using various base href configurations like <base href="#">, <base href="/& ...

Tips for saving a value within a jQuery function for future use in a different function

I have a situation where I receive a value from a jQuery function that I need to pass to another function. How can I achieve this? jQuery.getJSON(url+"&startDate="+startDate+"&endDate="+endDate+"&jobId="+jobId+"&type="+type, function(data) ...

What could be the reason behind npm trying to utilize a package version that is not specified in my package.json file?

My Angular and .NET 5 web application is encountering an issue when trying to install packages using the command npm i. The error message that appears is: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While re ...

Eradicate HTML by assigning empty values to certain attributes

Allowing the user to copy the HTML code of a div by clicking a button. Some attributes, such as for videos: <video loop muted autoplay> may appear like this after copying: <video loop="" muted="" autoplay=""> The ...

Utilizing the Onchange Event with Multiple Input Fields in Vanilla JavaScript

I'm working on a website where multiple inputs need to be created dynamically using createElement. Each input can have its own class, id, and other attributes. The main objective is to automatically calculate the overall price whenever a user adds a ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...

What are the steps to troubleshoot a Vue application?

I've encountered an issue with a code snippet that retrieves JSON data from a RESTful API. The code only displays the .container element and reports that the items array is empty, even though no errors are being shown. I attempted to debug the problem ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

Unable to connect to the cloud firestore backend specifically on the deployed version

When deploying the project using Vercel, I included my Firebase security and project details as environment variables on the Vercel dashboard. Authentication works fine during deployment, but there is an error in the console: @firebase/firestore: Firesto ...

What is the reason for TypeScript not throwing an error when an interface is not implemented correctly?

In my current scenario, I have a class that implements an interface. Surprisingly, the TypeScript compiler does not throw an error if the class fails to include the required method specified by the interface; instead, it executes with an error. Is there a ...

Animating a div using a changing scope variable in AngularJS

As a newcomer to Angular, I am looking to add animation to a div element using ng-click within an ng-repeat loop. Here is what I have attempted: app.js var app = angular.module( 'app', [] ); app.controller('appController', function($ ...

How to validate text from a <span> tag using Selenium WebDriver and JavaScript

Is there a way to retrieve the value from the span tag using this code snippet? var error = driver.findElement(webdriver.By.id('error-container-text')).getAttribute('innerHTML'); When I run the above code, I get a response that looks ...

Changing an AngularJS Protractor promise from a string to a decimal number - how to do it?

I am currently working with Angular.js Protractor to retrieve the values of cells in a grid. Although I can successfully retrieve these values, they are strings and I need to perform calculations with them. Upon attempting this: ptor.findElements(protrac ...

When using the hasMany/belongsTo relationship in VuexORM, the result may sometimes be

I have carefully followed the documentation and set up 2 models, Author and Book. The relationship between them is such that Author has many Books and Book belongs to an Author. However, despite having the author_id field in the books table, the associatio ...

Using TypeScript in combination with Angular for implementing CORS protocol

As I try to send a request to my REST endpoint, the following code is executed: this.http.request(path, requestOptions); The path is set to: http://localhost:8082/commty/cmng/users and the requestOptions are as follows: { headers: { user: "sdf", pas ...

Use the JavaScript .replaceAll() method to replace the character """ with the characters """

My goal is to pass a JSON string from Javascript to a C# .exe as a command line argument using node.js child-process. The JSON I am working with looks like this: string jsonString = '{"name":"Tim"}' The challenge lies in preserving the double q ...