Executing a function after another one has finished in Angular/TypeScript

I need to execute the f2 function only after the completion of f1, regardless of whether f1 is synchronous or asynchronous. To achieve this, I came up with a solution using a combination of Promise and a timer:

executeFunctions() {
    this.f1().then(result => {
        this.f2()
    })
}

f1() {
    return new Promise<any>((resolve, reject) => {

        // Code for f1...

        setTimeout( () => {
            resolve(x);
        }, 1500); // Simulating delay
    });
}

f2() {
    // Code for f2...
}

However, this approach always introduces a fixed delay of 1500ms. I am looking for a way to have f2 start immediately after the completion of f1, without any unnecessary waiting time. Is there a more precise way to synchronize the execution of these functions?

Answer №1

To eliminate the setTimeout component, simply remove it. This will trigger a call to either resolve or reject, transferring control flow to the next then or catch handler. If your Promise includes an asynchronous function, remember to invoke resolve/reject upon completion of that function.

Consider shortening the wait time from 1500ms - this duration represents the minimum time before the function can execute. Try increasing it to 2000ms. The timing is impacted by the main thread in which JavaScript operates. When the main thread is idle, any pending asynchronous tasks will be executed.

function f1() {
    return new Promise((resolve, reject) => {
        console.log('f1');
        resolve();
    });
}

function f2() {
   console.log('f2');
}

f1().then(res => f2());

Answer №2

When f1 operates synchronously, there is no need for any special handling:

global() {
    f1();
    f2();
}

If f1 is asynchronous and returns an Observable, utilize Rxjs operator, such as concatMap:

global() {
    f1().concatMap(() => f2());
}

For the scenario where f1 is asynchronous and returns a Promise, employ async/await:

async global() {
    await f1();
    f2();
}

In cases where f1 is asynchronous and returns a Promise (alternative):

global() {
    f1().then(res => f2());
}

Answer №3

Simply eliminate the timeout from the code snippet below:

function f1() {
    return new Promise((resolve, reject) => {
        console.log('i am first');
         resolve();
    });
}

function f2() {
    console.log('i am second');
}

f1().then(f2);

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

Using Angular 2: Applying a specific class to a single element with [ngClass]

I have a header table with arrows indicating sorting order, using Bootstrap icons. However, when I click on a column, all columns receive the icon class. Here is an example of what I mean: https://i.sstatic.net/CAS81.png Below is the code snippet: HTML ...

Creating TypeScript Unions dependent on a nested object's property

I want to create a Union Type that is dependent on a nested property within my object. Take a look at the example provided below: type Foo = { abilities: { canManage: boolean } } type Bar = { abilities: { canManage: boolean ...

Prevent Typescript from flagging unnecessary warnings about unassigned values that will never be assigned

One of my functions serves as a shortcut for selecting values from synchronous observable streams. The function in its entirety looks like this: export function select<T>(inStream: Observable<T>): T { let value: T; race( inStream, ...

Arranging an array of objects based on a specific keyword and its corresponding value

I have an array of objects that looks like this: [ { "type": "Exam", "value": 27 }, { "type": "Lesson", "value": 17 }, { "type": "Lesson", &qu ...

Explore how Angular can display the highlights of deepDiff results in JSON format!

I am utilizing deepDiff to display the variances between two JSON objects in a structured manner, which is working well so far. However, I am aiming to highlight these disparities within the parsed JSON contents, but it's not quite effective. How can ...

Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to th ...

What are the steps to troubleshoot a Node Package Manager library in Visual Studio Code?

I have created a Typescript library that I plan to use in various NodeJS projects. The source code is included in the NPM package, so when I install it in my projects, the source also gets added to the node_modules folder. Now, during debugging, I want to ...

Exploring the power of EJS with conditional logic

Can someone help me figure out why EJS is not evaluating to the else branch in my code? I'm using EJS version 3.1.5 with express version 4.17.1 and typescript. ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12 10| </head> 11| & ...

Angular 2 Aot Issue: CRITICAL ERROR: CALL_AND_RETRY_LAST Allocation unsuccessful - JavaScript heap exhausted

Encountered an issue while running Angular 2 AOT rollup: <--- Last few GCs ---> 144518 ms: Mark-sweep 1317.0 (1404.4) -> 1317.0 (1404.4) MB, 1522.9 / 0.0 ms [allocation failure] [GC in old space requested]. 146029 ms: Mark-sweep 1317.0 (1404 ...

How to effectively send an HTTP GET request to a REST API in Angular 2 and save the response in a JSON object

Currently, I am attempting to execute a GET request to the GitHub API using Angular2. The returned data is in JSON format, and my goal is to store it in a JSON object for further processing. While referring to the Angular2 documentation for guidance, I en ...

Error in Typescript occurring with a custom typography element

I recently developed a simple typography component for my React project and it's causing a Typescript error that's puzzling me a bit. Typography Component Code import clsx from 'clsx'; const sizeVariants = { h1: 'h1', ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

Differences Between ES5 and ES6 in Dealing with Arrays in JavaScript

I need assistance with converting the code snippet below as I suspect it is related to an ES5/ES6 compatibility issue. Any help would be highly appreciated. this.rows = Array.from(Array(Math.ceil(this.subCategoryModels.length / 3)).keys()); Upon attempti ...

Ways to delete a class in typescript

There's a menu on my website with li tags containing an a element for navigation. Everything is working fine, but I'm facing an issue where I need to remove all elements with the class seleccionado and only add it to the clicked li. I tried using ...

Show an error message in-line with a line break

I'm struggling to show inline error messages separately. What I want to achieve: Error 1 Error 2 However, they are currently displaying on the same line like this: Error 1 Error 2 I attempted to use document.createElement("br") without success. ...

Custom styles for PrimeNG data tables

Struggling to style the header of a datatable in my Angular project using PrimeNG components. Despite trying various solutions, I am unable to override the existing styles. Even attempting to implement the solution from this PrimeNG CSS styling question o ...

Is it necessary to validate a token with each change of page?

Currently facing a dilemma while working on my react-native app. Uncertain whether I should request the server to validate the token each time the page/screen changes, such as switching from 'feed' to 'profile', or only when actual requ ...

What are some ways to implement Material UI's Chip array to function similar to an Angular Chip Input?

Can the sleek design of Angular Material's Chip input be replicated using a React Material UI Chip array? I am attempting to achieve the modern aesthetic of Angular Material Chip input within React. While the Material UI Chip array appears to be the ...

Encountered an unexpected error while attempting to integrate my custom npm library "MyModule" into my Angular 2 project

I have created my own library which consists of one module and one component. After compiling my library, I add it to my main project using the following command: npm link ng-shared Next, when I attempt to import SharedModule in my module file as shown b ...

"Efficient TCP Communication with Asynchronous Operations in the .NET Framework

Just curious: is there a clear advantage to using asynchronous communication with the NetworkStream class (from TcpClient) rather than creating a separate thread and using synchronous operations like Read/Write? I've always thought that asynchronous o ...