Retrieving Data in Typescript Async Function: Ensuring Data is Returned Once All Code is Executed

I need help with waiting for data to be retrieved before returning it. The code below fetches data from indexedDB and sends it back to a component. I understand that observables or promises can accomplish this, but I am struggling with how to implement them properly. Currently, the return statement executes before the code above completes.

retrieveData() {
    let dbReq = indexedDB.open('myChatDb', 1);
    let db;
    let objectStore;
    let results;
    let transaction;
    let data = new Array();
   dbReq.onsuccess = function (event) {
      db = (event.target as IDBOpenDBRequest).result;
      transaction = db.transaction(["customer-messages"]);
      objectStore = transaction.objectStore('customer-messages');
      results = objectStore.openCursor();
      results.onsuccess = function (event) {
        let cursor = event.target.result;
        if (cursor) {
         data.push(cursor.value);
         cursor.continue();
        } else {
        console.log(data);
        console.log(data.length + " array length line 36");
        }
      }
      return data;
    }

Answer №1

To simplify the handling of event handlers, you can create a function that returns a promise and then use await:

function establishConnection(databaseName) {
    return new Promise((resolve, reject) => {
        let request = indexedDB.open(databaseName, 1);

        request.onsuccess = () => resolve(request.result);
        request.onerror = (event) => reject(new Error('Failed to connect to database'));
    });
}

function fetchObjectStoreData(objectStore) {
    return new Promise((resolve, reject) => {
        let results = objectStore.openCursor();
        let data = [];

        results.onerror => () => reject(new Error('Error fetching data from object store.'));
        results.onsuccess = () => {
            let cursor = event.target.result;
            if (cursor) {
                data.push(cursor.value);
                cursor.continue();
            } else {
                resolve(data);
            }
        };
    });
}        


async getData() {
    const db = await establishConnection('myDatabase');
    const transaction = db.transaction(["transaction-data"]);
    const objectStore = transaction.objectStore('transaction-data');
    
    return await fetchObjectStoreData(objectStore);
}

Answer №2

One way to accomplish this is by utilizing the power of async and await in your code structure. By converting the retrieveData function into an asynchronous function and strategically placing the await keyword where necessary, you can streamline the process of fetching data from a database.

async retrieveData() {
let dbReq = indexedDB.open('myChatDb', 1);
let db;
let objectStore;
let results;
let transaction;
let data = new Array();
await dbReq.onsuccess = function (event) {
  db = (event.target as IDBOpenDBRequest).result;
  transaction = db.transaction(["customer-messages"]);
  objectStore = transaction.objectStore('customer-messages');
  results = objectStore.openCursor();
  results.onsuccess = function (event) {
    let cursor = event.target.result;
    if (cursor) {
     data.push(cursor.value);
     cursor.continue();
    } else {
    console.log(data);
    console.log(data.length + " array length line 36");
    }
  }
  return data;
}

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

Reasons why making an AJAX call from Angular is not possible

I am trying to implement this component: import {Component} from 'angular2/core'; import {UserServices} from '../services/UserServices'; @Component({ selector: 'users', template: '<h1>HOLA</h1>' ...

Encrypting sensitive information in JavaScript and Angular 2: SecureString

Is there a way to securely copy sensitive data to the clipboard in javascript/Angular2, ensuring that the string remains confidential by removing it from computer memory when no longer needed? In Microsoft .Net, there is a feature called System.Security.S ...

Issue with displaying international characters when using HttpClient's http.get() function in Angular.The

I am facing an issue that I can't quite figure out as I am new to Angular. My goal is to read a local .csv file and display its contents in a table. Everything seems to be working fine, except for the fact that when special characters like "č, ć, š ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

Error encountered when trying to access children components in Typescript, even though React.FC is being

I am facing an issue with a child component that has the following structure: interface ChildProps extends AnotherInterface{ route: string, exitAction: ActionCreatorWithoutPayload, } const ChildComponent:FC<ChildProps> = ({title, shape, rout ...

Is it possible to dynamically adjust the size of the CircleProgressComponent element in ng-circle-progress?

For my current Angular 11 project, I am facing the challenge of dynamically changing the size of the ng-circle-progress library's CircleProgressComponent element. After some research, I discovered that the element's size can be adjusted by apply ...

Accessing user information after logging in can be achieved through utilizing Web API in conjunction with Angular 5 Token Authentication

Every time I access my Angular app, the following information is displayed: access_token:"******************" expires_in:59 refresh_token:"******************" token_type:"bearer" However, I am now facing an issue where I cannot extract the user id from t ...

Troubles arise with a Web API ASP .NET / Angular2 Session hosted on Azure

Hello, this is my first question here so please let me know if something doesn't fit. Currently, we are working on developing a Web API using C# and Angular2. One of the features requires the session to be efficient, but despite going through numerou ...

Can Material UI be defined as a peerDependency while maintaining its types as a DevDependency?

Is there a way to set Material UI as a peerDependency while keeping its types as DevDependency? I'm currently working on a component library using React + Typescript, with components based on Material UI and Rollup as the module bundler. For example ...

Utilizing an AwsCustomResource in AWS CDK to access JSON values from a parameter store

I found a solution on Stack Overflow to access configurations stored in an AWS parameter. The implementation involves using the code snippet below: export class SSMParameterReader extends AwsCustomResource { constructor(scope: Construct, name: string, pr ...

Using Angular 2's ngFor directive to iterate through arrays with access to first, last

In this example, I am attempting to make the first occurrence the default: plunkr However, I encountered the following error: Unhandled Promise rejection: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ...

Change the variable value within the service simultaneously from various components

There is a service called DisplaysService that contains a variable called moneys. Whenever I make a purchase using the buy button on the buy component, I update the value of this variable in the service from the component. However, the updated value does n ...

Having trouble with ESLint in VSCode? The ESLint extension seems to be ignoring linting rules after starting a new project within VSCode

I recently started using the ESLint extension in my VSCode editor for my React project. After creating the starter files, I ran the following command in my terminal: eslint --init This allowed me to choose the AirBnb style guide with React, which generat ...

``Is there a specific location where I can access the Microsoft Azure msal sign-up feature within Angular

My current Angular version is 5.2.0 and I am struggling to find a tutorial on how to incorporate Azure MSAL for new user sign-up using a Microsoft account. If anyone has any resources or examples on how to achieve this integration without having to update ...

getItemForm does not make a second promise call

I have a scenario where my function calls the api.send service twice, however when I run a test expecting it to resolve both promises, only res1 is returned and not res2. How can I ensure that both promises are resolved successfully? Here is my function: ...

RouterModule is a crucial external component that is essential for integrating

If I have a very simple component that is part of an Angular component library, it might look like this: mycomponent.module.html <div> <a routerLink="/"> </div> mycomponent.component.ts import { Component, OnInit, Input } from &a ...

Personalization of settings in material dialog

In my project, I am utilizing Angular and Material to create a seamless user experience. A key functionality I have implemented is the use of Angular Material dialogs across multiple screens. However, I am now faced with the challenge of needing to add a s ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Troubleshooting issue with getServerSideProps not functioning in Next.js while utilizing Next-redux-wrapper and TypeScript

When attempting to trigger an action as outlined in the documentation using the getServerSideProps function with the help of next-redux-wrapper store and redux-thunk, I am encountering the following TypeScript error: ts(2322): Type '({ req }: GetServe ...

Specify the dependencies in the package.json file to ensure that the React package designed for React v17 is compatible with React v18 as well

Recently, I developed an npm package using React v17.0.2. The structure of the package.json file is as follows: { "name": "shoe-store", "version": "0.1.0", "private": true, "dependencies": ...