Leaving the function prematurely without completion of the conditional statement

In my implementation, I have a basic function that invokes a method of a library. However, the issue arises when there is an if statement during execution.

The problem I am facing is that my function is being terminated before it exits the if statement. Is there a way to pause or make my function wait until the if statement is resolved?

Below is the code snippet:

public getHistory(): any {
  console.log('ENTER FUNC');
  this.channel.history((err: ErrorEvent, resultPage: any) => {
    if (err) {
      console.log(err.message);
    } else {
      this.messages = resultPage.items;
      console.log('EXIT IF');
    }
  });
  console.log('EXIT FUNCTION');
  return this.messages;
}

Here is the output: https://i.sstatic.net/QhQoT.png

I attempted to create an async function and used await on the library's method call hoping that the function would pause until the method returns. However, the function still concluded before completing the if statement.

Answer №1

If the function responsible for retrieving historical data does not return a promise (which is necessary for using async/await), you have the option to manually create a promise and resolve it within that function.

try {
  const responseData = await new Promise((resolve, reject) => {
    this.channel.retrieveHistory((error: ErrorEvent, historyData: any) => {
      if (error) {
        reject(error);
      } else {
        resolve(historyData);
      }
    });
  });

  this.messagesList = responseData.items;
  console.log('Exiting conditional block');
} catch (error) {
  console.log(error.message);
}

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

The Vitest test is not compatible with PrimeVue3 Dialogs and does not function as intended

I am currently working on a project that involves using PrimeVue components, and the time has come to conduct some tests. Below is the code for the test: import { beforeEach, describe, expect, it } from 'vitest' import type { VueWrapper } from & ...

How to set an already existing anonymous object to a property within the data property in VueJS

Help needed for a beginner question let myOptions: { chart: { height: 350, type: 'bar' }, colors: ["#800000"] }; let vueExample = new Vue({ el: '#example', components: { apexchart: VueApexCh ...

Drizzle-ORM provides the count of items in a findMany query result

Hello there, I'm currently experimenting with the Drizzle ORM and imagine I have this specific query const members = await trx.query.memberTable.findMany({ with: { comments:true } }) I'm wondering how I can retrieve the total count of me ...

What is the best way to create a memoized function in React?

I am currently developing an application using react and typescript, and I am facing a challenge in memoizing a function. const formatData = ( data: number[], gradientFill?: CanvasGradient ): Chart.ChartData => ({ labels: ["a", ...

Storing information in firebase using data structuring

While I initially passed an array to Firebase to store data, it proved to be inefficient when querying the data. As a result, I am now considering storing the data in mapping format. However, I am unsure of how to proceed with this. { "ClassDetails": ...

Discovering different types of navigation in React Navigation using navigationRef

I'm currently working on adding types to my TypeScript version of this function, but I'm facing some difficulties with it. Perusing the React Navigation documentation: // RootNavigation.js import { createNavigationContainerRef } from '@rea ...

Error encountered in React component: TypeScript TS2339 states that the property 'xyz' is not found on type 'IntrinsicAttributes...'

I am attempting to develop a straightforward React component that can accept any properties. The syntax below using any is causing issues (unexpected token just before <): export class ValidatedInput extends React.Component<any, any> {...} The p ...

What is the method to dynamically add an error to a FormGroup control using programming?

I am working with a dynamic FormGroup and I need to add an error to a form control programmatically. However, the current method I know of replaces any existing errors as shown below: this.userForm.controls.username.setErrors({ 'exists': &apos ...

Using React Router's useHistory hook, you can change the URL without triggering a component reload

I am looking to create a simple button that, when clicked, redirects a user to a specific route that I have defined in my Index.tsx file. After clicking the button, the URL bar correctly changes to "/dashboard", but the component (just an h1) does not app ...

Node.js: Handling Undefined Request Parameters

My get route is set up to receive two parameters "limit" and "page". router.get('/:limit/:page', userController.list); class UserController{ public list(req:Request, res:Response): void{ const limit:number = +req.params.limit || 25; ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

Is there a feature in VS Code that can automatically update import paths for JavaScript and TypeScript files when they are renamed or

Are there any extensions available for vscode that can automatically update file paths? For example, if I have the following import statement: import './someDir/somelib' and I rename or move the file somelib, will it update the file path in all ...

What is the process of invoking a function in Typescript?

I am curious about how to effectively call this function in TypeScript. Can you guide me on the correct way to do it? type Fish = { swim: () => void }; type Bird = { fly: () => void }; function move(animal: Fish | Bird) { if ("swim" in ...

Property referencing for change detection is a valuable technique

I'm struggling to update my template when changing a boolean property that is referenced in another array property. I expected the changes to reflect in my template, but they are not showing up. Upon initial load, everything appears in its initial st ...

Having difficulty transmitting data through SocketIO in NodeJS

My current project involves sending streams of data through SocketIO sockets. I'm working on a Node TS application that will handle large files, so the standard Buffer object won't cut it. Here's the code I have so far: Client Side socket. ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Typescript - optional type when a generic is not given

I am hoping for optionalFields to be of type OptionalFieldsByTopic<Topic> if a generic is not provided, or else OptionalFieldsByTopic<T>. Thank you in advance for the assistance. export interface ICreateItem<T extends Topic = never> { // ...

What is the proper method for typing unidentified exports that are to be used in TypeScript through named imports?

Currently, I am developing an NPM package that takes the process.env, transforms it, and then exports the transformed environment for easier usage. The module is structured like this: const transformedEnv = transform(process.env) module.exports = transf ...

Testbed: Issue encountered: Unable to resolve all parameters for PriDateInput component

I am facing an issue while creating an Angular Component with the help of TestBed. The error message I receive is as follows: Error: Can't resolve all parameters for PriDateInput: (?). error properties: Object({ ngSyntaxError: true }) ...

Patience is necessary as we await the initialization of the lazily loaded

I'm dealing with a scenario where I have a button triggering an onClick handler. In the onClick function, the first action is: if (this.state.lazyLoadedData === undefined) { await this.loadData(); } The issue arises when I click the button rapid ...