What is the reason that in Typescript, the get method is executed before the code within it?

Here is the code snippet:

let sqlLocalSelect = new SqlLocalSelect();
var variable = sqlLocalSelect;
console.log("variable " + JSON.stringify(variable));

This is the corresponding class:

import { SQLite } from 'ionic-native';

export class SqlLocalSelect {

database: SQLite;
private li_sitios: Array<Object> = [];

constructor() {}

get get_li_sitios(): Array<Object> {
this.database = new SQLite();
this.database.openDatabase({name: "data.db", location: "default"}).then(() => {
  this.database.executeSql('SELECT * FROM Markers;', [])
  .then((data) => {
    if(data.rows.length > 0){
      this.li_sitios = [];
      for(var i = 0; i < data.rows.length; i++) {
        var value:string = "no";
        if (data.rows.item(i).synchronised) {
          value = "si";
        } else {
          value = "no";
        }
        this.li_sitios.unshift({
          id: data.rows.item(i).id, 
          id_externa: data.rows.item(i).id_externa,
          id_owner: data.rows.item(i).id_owner, 
          name: data.rows.item(i).name, 
          lat: data.rows.item(i).lat, 
          lng: data.rows.item(i).lng,
          draggable: false, 
          synchronised: value,
          fecha: data.rows.item(i).fecha,
          hora: data.rows.item(i).hora
        });
      }
    } else {
      console.log("No data found");
    }
    console.log("Query executed successfully");
    console.log("li_sitios "+ JSON.stringify(this.li_sitios));

  }, (error) => {
    console.log("Error executing query: " + JSON.stringify(error));
  });
  }, (error) => {
    console.log("Error connecting to local database: " + JSON.stringify(error));
  });
  return this.li_sitios;
  }
}

Explanation of the issue: The output displays empty first and then shows the actual query results in console.

Sample Output

06-07 18:23:51.030 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60258)] "variable []", source: file:///android_asset/www/build/main.js (60258)
...
(Additional log messages and error details.)
...
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60834)] "Query executed successfully", source: file:///android_asset/www/build/main.js (60834)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60835)] "li_sitios [{...}, {...}, {...}]", source: file:///android_asset/www/build/main.js (60835)

Answer №1

Initially, the result of the get operation is empty and then the query results are displayed in the console.

This scenario is a typical aspect of asynchronous programming. A simple analogy would be:

const arr = [];
setTimeout(()=>{
   arr.push(1);
   console.log(arr); // [1]
}, 1000);
console.log(arr); // []

The order of code by line number does not dictate the execution sequence. While this may seem straightforward (and it truly is), many beginners tend to overlook this fact, hence worth emphasizing.

Answer №2

I am truly grateful for your assistance in resolving this issue.

  I was able to overcome the challenge with the following code:
  this.sqlLocalSelect = new SqlLocalSelect();
  setTimeout(()=>{
    var variable = this.sqlLocalSelect.get_li_sitios;
    console.log("variable " + JSON.stringify(variable));
  }, 1000);

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

Expanding code lines beyond 80 characters in Visual Studio Code with TSLint integration

I am utilizing TypeScript alongside TSLint and Prettier within Visual Studio Code for developing a React Native App. Despite my efforts to set up my editor to automatically wrap the code per line at 100 characters, it consistently reverts back to 80 chara ...

Error in Ionic 3 AdMob: Issue with Object(...) function

I've encountered a run-time error related to the AdMob plugin in Ionic 3. Adding this plugin results in an Object(...) is not a function error, while everything works fine without it. Can anyone provide a solution for this Run-time Error? app.module. ...

Exploring Angular2: Implementing oauth2 with token headers

As someone who is new to Angular 2, I found that things were much simpler with interceptors in version 1.*. All you had to do was add them and suddenly your headers were available everywhere, making it easy to handle requests especially when dealing with i ...

Could it be possible for a Firestore onUpdate trigger's change parameter, specifically change.after.data() and change.before.data(), to become null or undefined?

Presented below is a snippet of my cloud function exports.onUpdateEvent = functions.firestore.document('collection/{documentId}') .onUpdate((change, context) => { const after: FirebaseFirestore.DocumentData = change.after.data(); const ...

What is the best way to handle arithmetic operations with multiple input fields in Angular?

In my form, users input number values which I need to send to my ts file for multiplication when a button is clicked. View screenshot example Below are the code snippets: calculate(value0,value1){ this.bindData(value0,value1); } bindData(a,b){ ...

Exporting the default value from a TypeScript declaration file module

Imagine having a declaration file called foo.d.ts: declare namespace foo { interface Bar { (): void; } } declare var foo: foo.Bar; export default foo; Upon compilation: import Foo from './foo'; Foo(); The result is: "use strict"; va ...

Concealed Content Within Drawer Navigation

When using the Material UI permanent drawer component in different pages, I encountered an issue where the main content was getting hidden behind the drawer's toolbar and sidebar. I am unsure how to fix this problem. It seems like a styling issue, bu ...

Troubleshooting webpack encore issues with importing enums from node_modules

I am faced with a challenge of utilizing an enum from a library I created in a different project. The library is developed using Vue and typescript, bundled with rollup. On the other hand, the project is built with Symfony, with the front end also using Vu ...

Integrate a fresh global JSX attribute into your React project without the need for @types in node_modules

It is crucial not to mention anything in tsconfig.json. Error Type '{ test: string; }' cannot be assigned to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'test' does not exi ...

How to Change Background Color to Black for a PNG Image Using CSS in Ionic

When applying CSS in Ionic, I encountered an issue with the background image causing the background to turn black. Without the image, everything looks fine. ion-content { --background: url("/assets/product_background.png") 0 0/100% 95% no-re ...

Error: The function jquery_1.default is not recognized by webpack

I am encountering an issue with using external imports of jQuery in webpack. Despite trying different import syntaxes such as import $ from 'jquery', import * as $ from 'jquery, and const $ = require('jquery'), I continue to receiv ...

Is it true that in the Angular4 Webpack Starter, tsconfig.webpack.json is specifically designed for webpack, whereas tsconfig.json is intended for all other purposes

Please take a look at this git repository for more information: https://github.com/AngularClass/angular-starter The Angular4 Webpack Starter includes 2 important files: tsconfig.json and tsconfig.webpack.json These files have different configurations ...

Implementing the 'colSpan' attribute in ReactJS

I encountered an error saying "Type string is not assignable to type number" when attempting to include the colSpan="2" attribute in the ReactJS TypeScript code provided below. Any suggestions on how to resolve this issue? class ProductCategoryRow exten ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

The dropdown menu is obscured by the toolbar

When using ionic4/angular, I want a dropdown menu to display upon clicking on the ion-avatar. However, the dropdown menu is hiding in the toolbar. I have tried setting z-index but it did not work. Any suggestions would be appreciated. You can find the sta ...

Chaining based on conditions in JavaScript and TypeScript

How can I conditionally add a function to a chain in JavaScript? For instance, if modifier is true, I want myKey to be required using Joi.string().required(). If it is false, then just use Joi.string(): function customJoi(modifier) { return Joi.object({ ...

Having trouble displaying the button upon initial load using ngIf

My goal is to display a button when editing an input form. Initially, the button is hidden when the page loads but it should appear once any of the input fields are edited. I have also implemented highlighting for the input box that is being edited. Howeve ...

Tips for modifying TypeScript class types based on a parent class object property?

As part of a project, I have created two classes: ParentClass childrenClass which extends the ParentClass class Displayed below is the code for my ParentClass: interface ConfSetup<T extends boolean> { enabled: T; permissions: bigint[]; locati ...

Angular Form: displaying multiple hashtags within an input field

Utilizing Angular CLI and Angular Material, I have created a form to input new hashtags. I am facing difficulty in displaying previously added hashtags in the input field. Below is the code I have written: form.component.html <form [formGroup]="crea ...

OCI: Predict expenses based on a selection of virtual machines

Seeking to determine the anticipated cost of a selection of instances within OCI utilizing the TypeScript SDK. Oracle offers a tool called Cloud Cost Estimator for configuring and dynamically displaying cost estimates. Is it possible to achieve this throug ...