Commitments lead to mistakes

I encountered the following issue:

{"__zone_symbol__currentTask":{"type":"microTask","state":"notScheduled","source":"Promise.then","zone":"angular","cancelFn":null,"runCount":0}}

I have a defined class where I am invoking a method that returns a Promise....

export class TechPRODAO {
sqlite: any;
db: SQLiteObject;

constructor() {
    this.sqlite = new SQLiteMock();

    this.sqlite.create({
        name: 'techpro.db',
        location: 'default'
    }).then((_db: SQLiteObject) => {
        this.db = _db; 
    });
};

public executeSql(sqlstatement: string, parameters: any): Promise<any> {

    return this.db.executeSql(sqlstatement, parameters);
}

Below is where the call is made

export class AppointmentDAO {
techprodao: TechPRODAO;

constructor(_techprodao: TechPRODAO) {
    this.techprodao = _techprodao;
};

public insertAppointment(appointment: Appointment) {
    console.log("insertAppointment called");
    this.techprodao.executeSql("INSERT INTO appointment (ticketnumber, customername, contactemail, contactphone, status, location, paymenttype, description, hascontract) " +
        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", [appointment.ticketnumber, appointment.customername, appointment.contactemail, appointment.contactphone, appointment.status,
            appointment.location, appointment.paymenttype, appointment.description, appointment.hascontract])
        .then((data) => {
            console.log("Inserted into appointment: ticketnumber=" + appointment.ticketnumber);
        }, (error) => {
            console.log("ERROR in insertAppointment: " + JSON.stringify(error));
        });
}

The error occurs during the executeSql function in insertAppointment, and I am puzzled as to why it is not properly triggering the "then" statement.

Answer №1

It is not recommended to include asynchronous operations in the constructor because it can be difficult to determine when they will be completed. Instead, consider initializing them outside of the constructor:

export class TechPRODAO {
  sqlite: any;
  db: Promise<SQLiteObject>;

  constructor() {
    this.sqlite = new SQLiteMock();

    this.db = this.sqlite.create({
      name: 'techpro.db',
      location: 'default'
    });
  }

  public executeSql(sqlstatement: string, parameters: any): Promise<any> {
    return this.db.then(db => executeSql(sqlstatement, parameters));
  }
}  

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

Debugging client-side TypeScript with Node

Is it possible to debug client-side .ts typescript files directly from Visual Studio (2015) with breakpoints and watches? Most solutions online recommend using browser devtools like Chrome. But can it be done in Visual Studio? After creating a .ts script ...

Direct the routing of static files to the root directory, implement HTML5 routing, and incorporate Angular2

Currently, I am in the process of creating an Angular 2 application that utilizes html5 routing. A challenge that I have encountered revolves around nested routes. Specifically, while a route like /route1 functions properly, issues arise when attempting to ...

Step-by-step guide: Setting up Typescript with npm on your local machine

I am trying to set up Typescript without any global dependencies. To do so, I have included the following in my package.json file: { "name": "foo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \" ...

What is the best access modifier to use for TypeScript properties and functions in Angular 2 that will be accessed in the view?

Which access modifier is recommended for ng2 properties and methods that should only be used from the view? I usually use private, but came across this post advising against it: Angular2 - should private variables be accessible in the template? However, ...

What is the best way to extract longitude and latitude from a string using Angular 4 TypeScript?

Currently I am diving into the world of Angular 4 and experimenting with Google Maps integration. I came across a helpful tutorial on how to incorporate Google Maps into my project successfully. However, I now face a new challenge. I have strings of addres ...

Enhance the express request to include the user parameter for the passport

I am currently utilizing Passport for authentication in an Express application. This authenticates the user and sets it on the Express response. As I am using TypeScript, trying to set the request type to Request in the route definitions results in an erro ...

The type 'datetimepicker' is not recognized for 'JQuery<HTMLElement>' and is therefore non-existent

Looking for guidance on utilizing the eonasdan-bootstrap-datetimepicker library in conjunction with Angular 6? Want to establish default options? Access the library at: https://github.com/Eonasdan/bootstrap-datetimepicker Provided below is the code snipp ...

Angular 6: TypeError - The function you are trying to use is not recognized as a valid function, even though it should be

I'm currently facing a puzzling issue where I'm encountering the ERROR TypeError: "_this.device.addKeysToObj is not a function". Despite having implemented the function, I can't figure out why it's not functioning properly or callable. ...

Injecting a service into a parent class in Angular 6 without the need to pass it through the constructor

Can anyone provide guidance on how to incorporate a service with multiple dependencies into an abstract class that will be inherited by several classes, in a more streamlined manner than passing it through all constructors? I attempted to utilize static m ...

Is it possible to view the list of errors displayed by vscode when opening a JS file exclusively through the terminal?

Is there a default configuration file that vscode uses to display errors and warnings? I want to identify all issues in my JavaScript project. I don't have any jsconfig.json or tsconfig.json files, only using the //@ts-check directive in some files. ...

Is it recommended to include modules in the Imports section of SharedModule in Angular?

Welcome to my SharedModule! import { CommonModule } from "@angular/common"; import { NgModule } from "@angular/core"; import { FormsModule, ReactiveFormsModule } from "@angular/forms"; import { IconModule } from "@my-app/components/icon/icon.module"; impo ...

Exploring the application of keyof with object structures instead of defined types

Looking to create a new type based on the keys of another object in TypeScript. Successfully achieved this through type inference. However, using an explicit type Record<string, something> results in keyof returning string instead of a union of the ...

Challenges with implementing Typescript in Next.js and the getStaticProps function

Having trouble with the implementation of getStaticProps where the result can be null or some data. The typings in getStaticProps are causing issues, even after trying conditional props. Any suggestions? type ProductType = { props: | { ...

Converting Blob to File in Electron: A step-by-step guide

Is there a way to convert a Blob into a File object in ElectronJS? I attempted the following: return new File([blob], fileName, {lastModified: new Date().getTime(), type: blob.type}); However, it appears that ElectronJs handles the File object differently ...

Display the concealed mat-option once all other options have been filtered out

My current task involves dynamically creating multiple <mat-select> elements based on the number of "tag types" retrieved from the backend. These <mat-select> elements are then filled with tag data. Users have the ability to add new "tag types, ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Using TypeScript to implement Angular Draggable functionality within an ng-template

Sorry if this question has been asked before, but I couldn't find any information. I am trying to create a Bootstrap Modal popup with a form inside and I want it to be draggable. I have tried using a simple button to display an ng-template on click, b ...

Is there a problem with the props being passed? Can someone verify this

Blockquote Having trouble passing props, Parent component: props: { data: { type: Object as PropType<FormatOrderItem>, default: () => {} } I'm facing an issue when trying to pass props from the parent component to the ch ...

The React Component in Next.js does not come equipped with CSS Module functionality

I have been attempting to incorporate and apply CSS styles from a module to a React component, but the styles are not being applied, and the CSS is not being included at all. Here is the current code snippet: ./components/Toolbar.tsx import styles from & ...

The Angular Observable continues to show an array instead of a single string value

The project I am working on is a bit disorganized, so I will try to explain it as simply as possible. For context, the technologies being used include Angular, Spring, and Maven. However, I believe the only relevant part is Angular. My goal is to make a c ...