Calling synchronous methods in Typescript

Hello Nativescript Team,

I seem to be stuck with making method calls in my code.

Could you please provide me with guidance on how to implement synchronous method calling in Nativescript + Angular?

import { Component, OnInit, AfterContentInit } from "@angular/core";

@Component({
    selector: "Home",
    moduleId: module.id,
    templateUrl: "./home.component.html",
    styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, AfterContentInit {

constructor() {
    this.firstMethod();
    this.secondMethod();
    this.thirdMethod();
    this.fourthMethod();
}

ngOnInit(): void {
    this.firstInitMethod();
    this.secondInitMethod();
    this.thirdInitMethod();
    this.fourtInitMethod();
}

private firstInitMethod() {
    console.log("1 ::::: firstInitMethod method");
}

private secondInitMethod() {
    console.log("2 ::::: secondInitMethod method");
}

private thirdInitMethod() {
    console.log("3 ::::: thirdInitMethod method");
}

private fourtInitMethod() {
    console.log("4 ::::: fourtInithMethod method");
}


private firstMethod() {
    console.log("1 ::::: First method");
}

private secondMethod() {
    console.log("2 ::::: second method");
}

private thirdMethod() {
    console.log("3 ::::: third method");
}

private fourthMethod() {
    console.log("4 ::::: fourth method");
}


ngAfterContentInit() {
    console.log("ngaftercontnet init method called");
    this.firstAfterInitMethod();
    this.secondAfterInitMethod();
    this.thirdAfterInitMethod();
    this.fourthAfterInitMethod();
}


private firstAfterInitMethod() {
    console.log("1 ::::: firstAfterInitMethod method");
}

private secondAfterInitMethod() {
    console.log("2 ::::: secondAfterInitMethod method");
}

private thirdAfterInitMethod() {
    console.log("3 ::::: thirdAfterInitMethod method");
}

private fourthAfterInitMethod() {
    console.log("4 ::::: fourthAfterInitMethod method");
}

Output result:

[My Phone 5508]: 1 ::::: First method
[My Phone 5508]: 2 ::::: secondInitMethod method
[My Phone 5508]: 3 ::::: thirdInitMethod method
[My Phone 5508]: 3 ::::: third method
[My Phone 5508]: 2 ::::: second method
[My Phone 5508]: 4 ::::: fourtInithMethod method
[My Phone 5508]: 4 ::::: fourth method
[My Phone 5508]: ngaftercontnet init method called
[My Phone 5508]: 1 ::::: firstAfterInitMethod method
[My Phone 5508]: 2 ::::: secondAfterInitMethod method
[My Phone 5508]: 1 ::::: firstInitMethod method
[My Phone 5508]: 3 ::::: thirdAfterInitMethod method
[My Phone 5508]: 4 ::::: fourthAfterInitMethod method

I am looking for a way to synchronously call the methods as follows :

First methods in Contructor()

        this.firstMethod();
        this.secondMethod();
        this.thirdMethod();
        this.fourthMethod();
Second methods in Init

        this.firstInitMethod();
        this.secondInitMethod();
        this.thirdInitMethod();
        this.fourtInitMethod();
Third methods in AfterInit

        this.firstAfterInitMethod();
        this.secondAfterInitMethod();
        this.thirdAfterInitMethod();
        this.fourthAfterInitMethod();

Answer №1

In order to ensure that a method has completed its process, it is necessary to return either a Promise or an Observable.

For example:

private performAction() {
  return new Promise((resolve, reject) => {
    console.log("1 ::::: Perform Action method");
    // resolve("result"); if you wish to return something.
  });
}

All methods like performAction() should return a Promise in your scenario.

To call the performAction method, follow this structure:

this.performAction().then((resolve:any) => {
  // proceed with another action here
});

Remember: TypeScript and JavaScript are asynchronous languages, so utilize Promises for synchronized tasks.

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

Is it possible to view JavaScript methods in the watch window of IE's debugger?

Can I view custom methods in the IE developer toolbar's watch window? For example, if I have a global function named hello, can I locate it within the DOM? function hello() { alert("hello"); } If so, where in the watch window would I find them? ...

Problem with FB.logout, FB.getLoginStatus() is yielding an unrecognized status

I've been struggling to implement the functionality of FB.logout() in my project. Every time I try, I encounter the error message: 'FB.logout() called without an access token.' After researching solutions online, I discovered that I need to ...

Leveraging current state data (from store) in ReactJS promptly

Working in React with Flux and faced with a challenge. Within my component, I have a function triggered by a click event: onClickEventEdit: function(itemId) { ScheduleActions.getEventById(itemId) // sets the retrieved data into `currentEventById ...

Is it possible to toggle between namespace and class using parentheses?

While working with older javascript code, I stumbled upon the following snippet: // module1.js class Class { constructor() { console.log('hello') } } const exported = { Class: Class, } module.exports = exported This code is then ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

Ensure that a JavaScript prompt appears when a form is selected in a dynamic HTML field

My PHP script generates a table form with results from a database query for users to edit records. The form can display up to 30 records. If the VoidTag checkbox is checked when the form is submitted, I want the user to confirm this action. If it is not ...

Hide a div using jQuery and then reveal it when clicked

I am trying to create a sliding effect for a div that appears behind another div when an arrow is clicked, and then hides again when a form button is clicked. While I can code most of this functionality, I am struggling with the specific implementation of ...

Assign the returned auth2 value to an Angular variable

I've been searching for a solution to my issue without much success, even though it seems like it should be an easy fix. Currently, I am using AngularJS and Google auth2 for authentication to fetch the logged in user's information. My goal is to ...

A guide to displaying the combined values of identical items across multiple dates using react.js

Here is an example of an array I have: array = [ { "id": 1, "date": { "id": 1, "name": "202001" }, "item": { "id": 1, "name": "I1 ...

Is it possible to verify age on a date field in vanilla JavaScript?

How can I validate the age on a date input field? If someone is 18 or older, they will be valid. Otherwise, an error message should be displayed. Can you help me with this? ...

Modifying the ngFor directives in Angular for a fresh look

I successfully implemented the *ngFor feature and it's functioning properly: <div class="dummy__1" *ngFor="let item of dummy.pic; let i = index"></div> Now, I am looking to modify the class="dummy_1" to produce the following format: < ...

Issue with Masonry layout not adjusting to change in window size

Something seems to be fixed on displaying four rows, no matter the size of the window. Previously, it would adjust to three rows or fewer as the browser was resized. I recently played around with columnWidth, but reverting it back to 250 doesn't seem ...

The Javascript and CSS code for a button fails to trigger the animation function after the initial click

Is it possible to trigger the animation function multiple times after the initial click without making changes to the HTML code? The ID and class in the code must remain as they are. I attempted to use the display property set to none, but it did not yie ...

Identify and track colored dots within an image using tracking.js

I'm working on creating a program that can tally the number of dots on dominoes in an image, such as the one shown here: https://i.sstatic.net/NKHXl.jpg My goal is to develop this functionality using JavaScript. I've attempted to learn how to u ...

What is the best way to save characters from different languages into variables?

I created an application that reads words from a TXT file and stores them in a database. The issue arises when I encounter words from other languages that contain non-English characters, resulting in the following problem: Is it possible to store these ch ...

Angular API for search filtering input

I am currently retrieving data from an API in my service. I now need to implement a search filter by name. Here is the code for the Service: export class ListService { listUrl = 'https://swapi.co/api/planets'; constructor(private ht ...

Error: The property 'express-validator#contexts' cannot be read because it is undefined

I'm currently working on validating some data with the express-validator middleware v6.10.1, but I'm encountering an unusual error when testing it with Postman. Here's my code: const { check, validationResult } = require('express-valid ...

Protractor functions perfectly on localhost, but encounters a Timeout error when used remotely - the asynchronous callback was not executed within the specified timeout period

Running protractor protractor.conf.js --baseUrl=http://localhost:4200/ executes successfully by filling data, validating elements, etc. However, when attempting to test the same website through a remote URL protractor protractor.conf.js --baseUrl=http://t ...

The controller is unable to access the value bound to the controller in AngularJS

Implementing controllerAs in my directive along with bindToController. However, the bindToController parameter is coming up as undefined in the controller. See the DEMO for more details. var myApp = angular.module('myApp',[]); myApp.controller( ...

The functionality of one button triggering the opening of two dropdown menus simultaneously is being successfully implemented

My issue is that I have created two different dropdowns, but they both open the same dropdown menu. Here is my code; <div class="d-flex"> <button class="btn btn-icon btn-group-nav shadow-sm btn-secondary dropdown-toggle" type="butto ...