Essential use of async-await with IndexedDB operations

Within my React TypeScript App, I utilize IndexedDB for data storage. To work with IndexedDB, I have a dedicated class called DB. One of the methods in this class is used to retrieve all data.

 public getAll(){

 const promise = new Promise((resolve,reject)=>{
    const req = this.openDB();
    req.addEventListener("error", (e) => {
      console.log("error ", e);
      reject ("error");
    });

    req.addEventListener("success", () => {
      const db = req.result;
      const tx = db.transaction("tasks", "readonly");
      tx.addEventListener("complete", () => {
        console.log("transaction complete");
        db.close();
      });

      const readObj = tx.objectStore("tasks");
      const data = readObj.getAll();
      
      data.addEventListener("success",(e)=>{
        console.log(data);
        console.log(e);
        resolve (data.result);
      });

    });
 });

 return promise;

} 

In one of my component's event handlers:

      const db = new DB();
      const dataPro = db.getAll();
      dataPro.then((resData)=>{
      console.log(resData); // Data successfully retrieved
                           }

Although the getAll function runs smoothly without the use of async-await, I wonder if it's truly necessary to include async-await in this function. Are there specific scenarios where async-await is required?

I have tested the getAll function without async-await and it still functions properly for me.

Answer №1

Using the async and await keywords is like adding a layer of sweetness to working with Promises, making it cleaner and more efficient. While they are not mandatory, they do come in handy quite often. However, if a function simply creates and returns a Promise, then using these keywords may be unnecessary.

The example given here already shows some redundancy - awaiting the same Promise twice. Once in this part of the code:

const promise = await new Promise((resolve,reject)=>{

And once again here:

return await promise;

Moreover, since the function is marked as async, you still need to await it (or use a callback) when calling it:

dataPro.then((resData)=>{

As evident from this repetition, all this seems redundant and unnecessary. If the function itself doesn't internally await anything, there's no need for it to be flagged as async. It can simply return the created Promise:

public getAll(){
  return new Promise((resolve,reject)=>{
    // rest of the code within the Promise
  });
}

This way, the usage of the function remains unchanged.

If the vendor offers a Promise-based API, then utilizing the async and await keywords can greatly simplify and enhance the readability of the code. In instances where such an API is not available, wrapping other asynchronous operations (using callbacks/events/etc.) in a manual Promise and returning it allows consuming code to optionally leverage async and await (similar to what is being done here), which follows a common pattern.

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

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Making a jQuery AJAX request for JSON from a separate domain

My goal is to send an AJAX request to , expecting JSON data in return (not sure if JSONP) However, when I click on the button to make the AJAX request, I encounter this issue: http://prntscr.com/8xswr1 (Google Chrome Console) Upon double-clicking ' ...

Passing URL parameters from App.js to routes/index.js

I have a URL that looks like this: http://localhost:3000/?url=test In my Express application's app.js file, I'm attempting to extract the "test" parameter from the URL and pass it to my routes/index.js. Currently, I can easily send a static var ...

Acquire dynamically loaded HTML content using Ajax within a WebView on an Android

I have been attempting to extract the content of a web page on an Android platform. Despite trying JSoup, I faced a limitation with ajax support. As an alternative, I am endeavoring to embed the URL within a hidden web view and retrieve the HTML in the on ...

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

What is the best way to initiate animation on a child element once the parent element has reached 75% completion of its animation

Is there a way to use JavaScript to determine when an animation is 75% complete? I have many nested HTML elements that need to be animated with an animation delay property, where the nested animation should start when the parent element is 75% complete. I ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

Cleaning up HTML strings in Angular may strip off attribute formatting

I've been experimenting and creating a function to dynamically generate form fields. Initially, the Angular sanitizer was removing <input> tags, so I discovered a way to work around this by bypassing the sanitation process for the HTML code stri ...

Angular 2 template format standard

Every Angular 2 example I encounter seems to place the template within the component decorator. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>Hello world</h1>' }) e ...

What is the most efficient way to retrieve a substantial volume of data from Mongodb quickly, especially when the query results require processing before transmitting to the client?

My project involves a large Mongodb database paired with a React front-end and Node back-end, housing around 100000 documents. Indexing has been completed and Redis is already in use. The search feature implemented allows users to find relevant documents b ...

The authentication for npm failed with a 401 error code when attempting to log in

When attempting to sign in to npm using the command npm login and providing my username, password, and email, I am encountering the following error message: The Registry is returning a 401 status code for the PUT request. Even though I have used the sa ...

Unable to retrieve props from server-side page to client-side component in a Next.js application router

Currently, I am utilizing app router alongside Next.js version 13.5. Within my /dashboard page (which is a server component), there is an ApiKeyOptions client component embedded. However, when attempting to pass props from the dashboard page to the ApiKeyO ...

Exiting or returning from a $scope function in AngularJS: a guide

There are times when I need to exit from my $scope function based on a certain condition. I have attempted to achieve this using the return statement. However, my efforts have been in vain as it only exits from the current loop and not from the main scop ...

Is it possible to generate various resolutions of an image simultaneously?

While trying to download wallpapers from a link on this website, I encountered an issue. Upon clicking the download button, a new page opened with the URL "https://images.wallpapersden.com/image/download/street-fighter-fortnite_bGtoaW6UmZqaraWkpJRmbmdlrW ...

The issue I am facing is that whenever I use an AJAX POST request,

I encountered an issue where the ajax post method was unable to pass a parameter to the controller, as the controller parameter always appeared as Null. Index.schtml: I attempted to initiate a new view via a parameter by triggering an element in HTML and ...

Select the small image to reveal the larger overlay image

I have a grid of images and I want each image to expand into fullscreen when clicked. However, the JavaScript I am using is causing only the last image in the grid to overlay. How can I resolve this issue? Here is the code I am currently using: http://js ...

How to trigger a function when clicking on a TableRow in React using MaterialUI

Can someone help me understand how to add an onClick listener to my TableRow in React? I noticed that simply giving an onClick prop like this seemed to work: <TableRow onClick = {()=> console.log("clicked")}> <TableCell> Content </Ta ...

Sequential execution of multiple useState updates when an update triggers a re-render

Can you explain why the function setPeople is being executed after setFirstName, setEmail, and after the event handler has been exited? const [firstName, setFirstName] = useState(''); const [email, setEmail] = useState(''); const [peopl ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...