Malfunction in returning values observed when calling a synchronous function from an asynchronous function

I need to implement a validation process where the app checks the database for a specific value every 2 seconds until it is found.

let confirmation = false;
do {
  await this.sleep(2 * 1000);
  confirmation = this.validateSession(hash);
  console.log(confirmation);
} while (!confirmation);    
validateSession(hash) {
  let sqlQuery = "SELECT user_id FROM session WHERE hash='" + hash + "';";

  this.db.execute(sqlQuery).then(response => {
    if (response[0].user_id !== null) {
      console.log("Expected to return true");
      return true;
    }
  }).catch(error => {
    return false;
  });

  return false;
}

The issue I am facing is that the function always returns false, even though the message

console.log("Expected to return true");
shows up. I suspect it's because I am calling a non-async function inside an async function. Any suggestions?

Answer №1

It seems like your assumption is spot on. The key here is to ensure that your checkSessao function returns a Promise and then wait for it to be resolved within your loop.

checkSessao(hash) {
  return new Promise((resolve, reject) => {
    let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";    
    this.db.selectGenerico(sql).then(response => {
      if(response[0].usuario_id !== null) {
        console.log("supposed to return true");
        resolve(true);
      } else {
        resolve(false);
      }
    }).catch(ex => {
      resolve(false);
    });
  })
}

How to use it:

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = await this.checkSession(hash);
  console.log(conf);
} while (!conf);

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

Issue: Unspecified information - Strategies for troubleshooting - Angular

Using a web service, I need to showcase specific data such as: LABEL, ISINCODE, REF. When represented in JSON format, the structure appears as follows: MET = [ { LABEL: "WILHELMSEN", ISINCODE: "NO0010571698", RESOLUTION: ...

Merging arrays from observables without the need to wait for all of them to finish

Within my application, I have established a process where data is fetched from a remote server at regular intervals. The retrieved data is structured as an array of objects and is then showcased in the HTML template using the angular async pipe. To enabl ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...

Choosing between global and local Node packages can be a crucial decision that affects

Recently, I discovered that Angular 2 is installed globally on my system, but I can't remember when I did that or if it's the recommended setup. It seems redundant since Angular can be defined in each project individually. This situation has me ...

Encountering an Error While Trying to Add Typescript Support to Create React App Using Yarn

Encountering an issue while setting up a new Typescript/React project. Here's the error message: Installing template dependencies using yarnpkg... yarn add v1.22.19 [1/4] Resolving packages... [2/4] Fetching packages... error <a href="/cdn-cgi/l/em ...

Adding properties to React Component

Due to security reasons, I am required to update the ant design library in my codebase from version 3 to 4. In the past, this was how I used the icon: import { Icon } from 'antd'; const Demo = () => ( <div> <Icon type="smile" ...

Using Qwertz layout on Protractor, sending an exclamation mark is not possible

Trying to input an exclamation mark in a field using Protractor is proving to be difficult for me. Here's what I'm attempting: element(by.id('nom')).sendKeys('abc!'); But all I see in the field is abc. Upon adding a keyup ...

Transferring data from index.ts using export and import operations

While working on my angular project, I encountered a rather peculiar issue. I have organized my project into separate modules for layouts, login, and dashboard. Specifically for the login page, I wanted to implement a unique layout. Here's how I tried ...

"AngularJS's ng-click, ng-controller, and ng-app directives are essential

I am facing an issue with getting angularJS to recognize a variable that is defined in ng-app, ng-controller, or ng-click. I have tried three sets of codes so far: <table> <thead> <tr> <script> var ap ...

Angular - The confirmDialog from Primeng is appearing hidden behind the modal from ng-bootstrap

I am currently utilizing the primeng and ng-bootstrap components to develop an angular-based website. In order to collect data, I have implemented a form within an ng-bootstrap modal. However, upon clicking the "save" button on the modal, the primeng conf ...

How to set the default theme color for the mat-sidenav background in Angular 6 and 7?

Is there a way to make the background of a mat-sidenav match the theme color of my mat-toolbar? In the file src\styles.scss, I have the following: @import '~@angular/material/prebuilt-themes/indigo-pink.css'; The template / HTML file incl ...

"Launching" conduit for Observable

Is there a way to attach two pipes to an HttpClient request in order to execute functions at the beginning and end of the request? I have discovered the "finalize" operator for executing a function when the request is finished, but I am looking for an equi ...

Challenges with importing VideoJs VR in Angular

Apologies for what may seem like a silly question, but I'm relatively new to Angular and I'm encountering some issues with VideoJs VR. Everything works fine with VideoJs, but when attempting to use VR for a 360-degree video, I'm seeing the f ...

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...

Angular2 - HTML not displaying the response

I am currently mastering angularjs2. In my latest project, I attempted to fetch data from an API and received a response successfully. However, I encountered an issue where the response is not rendering in homepage.component.html as expected. I am unsure o ...

Show the selected options in material checkboxes and automatically update the checkbox values when any of them is changed using Angular Material

I am brand new to Angular and I'm currently attempting to display all the data and update the value of a checkbox when it is checked or unchecked. Here's my code: DatasetComponent.ts: export class DatasetComponent implements OnInit { displayed ...

Ensure the privacy of your app with Ionic secure storage by prompting the user to establish a personalized lock

I'm running into an issue while trying to set up the secure storage plugin. If initialization fails, it typically indicates that the user hasn't configured a secure lock screen. Following guidelines from the project's GitHub page, I am attem ...

An asynchronous function will consistently yield an observable result

Below is an asynchronous function that was designed to populate the userList through the backend. However, when it is called using await this.getUsers(); within the ngOnInit method, the userList returns as an Observable. What crucial part seems to be mis ...

Need help with resetting a value in an array when a button is clicked?

Using Tabulator to create a table, where clicking on a cell pushes the cell values to an array with initial value of '0'. The goal is to add a reset button that sets the values back to '0' when clicked. component.ts names = [{name: f ...