Sequential Execution of TypeScript Promises not Working as Expected

Currently, I am learning Promise with TypeScript and I am facing an issue where the promises in my code are not executing sequentially as expected. Despite researching online for 2 days, I have been unable to find a solution. If anyone could provide some insight or suggestions, I would greatly appreciate it. Thank you.

step1()
.then(() => {
      return step2();
})
.then(() => {
      return step3();
});

function step1() : Promise<void>{
        return new Promise<void>(() => {
                setTimeout(() => {console.log("1");}, 1000);
        });
}

function step2() : Promise<void>{
        return new Promise<void>(() => {
                setTimeout(() => {console.log("2");}, 1000);
        });
}

function step3() : Promise<void>{
        return new Promise<void>(() => {
                setTimeout(() => {console.log("3");}, 1000);
        });
}

The execution seems to be stuck at step 1 without proceeding to the next steps. No other functions are being called after step 1.

Answer №1

Even if the commitment you made is no longer valid, it is still important to use the resolve function to signal the completion of the task.

Instead of

return new Promise<void>(() => {
        setTimeout(() => {console.log("1");}, 1000);
});

Consider using

return new Promise<void>((resolve) => {
        setTimeout(() => {console.log("1"); resolve()}, 1000);
});

in every single function

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

Can a type be formed with a generic type as the rest parameter?

After exploring the question about implementing a choice of index type on an interface Defining a choice of index type on an interface Now, I am tasked with creating a sequence of elements. Typically it would look like element1 & element2, but because ...

What is the best way to enable code sharing between two TypeScript projects housed within the same repository?

Our project has the following structure: api (dir) -- package.json -- tsconfig.json -- src (dir) -- client (dir) ---- package.json ---- tsconfig.json ---- src (dir) The "client" directory houses a create-react-app project that proxies to the API d ...

Issue with Angular custom tag displaying and running a function

I have created a custom HTML tag. In my next.component.ts file, I defined the following: @Component({ selector: 'nextbutton', template: ` <button (click) = "nextfunc()">Next</button> ` }) export class NextComponent{ nextfunc( ...

TypeScript - passing a specific type of a union type to a nested function

const function = <T>( input: string | ArrayLike<T> ) => (output: string | ArrayLike<T>, position = 0) => { // perform operations with input and output } const result = function ('abc') In this scenario, the resulting ...

What is the process for utilizing ts-node ESM in conjunction with node modules?

Disclaimer: I understand that the question below pertains to an experimental feature. I have initiated a thread on the ts-node discussion forum. Nonetheless, I believe that posting on StackOverflow will garner more visibility and potentially result in a qu ...

The 'Alias[]' type does not share any properties with the 'Alias' type

I encountered an issue: The error message 'Type 'Alias[]' has no properties in common with type 'Alias'' appeared. Here is my Alias setup: alias: Alias = { id: 0, domain_id: 0, source: '', dest ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

Error: The template could not be parsed due to the following issues: Element 'mat-card' is not recognized

Every time I run Karma "ng test" for my project, an error keeps popping up: Error message: Failed - Template parse errors: 'mat-card' is not a known element Interestingly enough, the application seems to work perfectly fine with the mat-card ta ...

Managing Angular signals: updating an element in an array that belongs to an object

Could it be that I am overcomplicating things by using complex signals? Please advise if what I am attempting to achieve is not a suitable use-case for Angular's Signals. However, I strongly believe that it should be achievable! I have a service in p ...

Issue discovered: Safari displays a TypeError when a GET request is made to the API server within an Angular 5 application

Currently, I am developing a web app using Angular 5 and facing an issue while trying to call the server's API endpoint. Whenever I receive an error response (400+), it seems that on Safari the app breaks and throws an error. ERROR - TypeError: Type ...

Utilize localStorage.getItem() in conjunction with TypeScript to retrieve stored data

Within my codebase, I have the following line: const allGarments = teeMeasuresAverages || JSON.parse(localStorage.getItem("teeMeasuresAverages")) || teeMeasuresAveragesLocal; Unexpectedly, Typescript triggers an alert with this message: Argument ...

Challenges arise when attempting to break down an API into separate components rather than consolidating it into a

I've been struggling with this issue for a few days now. Problem Explanation: I am trying to use Axios to fetch data and store it in the state for each individual Pokémon. However, currently all the data is being rendered inside a single component w ...

When working in VScode, there may be difficulty in locating project-specific imports for `tsx` files. However, the TypeScript compiler is able to locate

When converting a jsx component to tsx, my VScode editor highlights project-specific imports as errors. The following code is from components\molecules\WizardSteps.jsx JSX https://i.stack.imgur.com/tKZ35.png TSX The following code is from comp ...

Unidentified Controller Scope in Angular and TypeScript

I am struggling with my Angular 1.5 app that uses Typescript. Here is a snippet of my code: mymodule.module.ts: angular.module('mymodule', []).component('mycomponent', new MyComponent()); mycomponent.component.ts export class MyCont ...

Angular2 - Utilizing the "withCredentials" Request Setting

I encountered a CORS problem while attempting to connect to Neo4j in an Angular2 component: Response to preflight request doesn't pass access control check. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header ...

A step-by-step guide on properly specifying the return value of a factory method

I have a base class with the following structure: class Base { protected constructor() {} static create() { return new this; } } However, when I extend this class and attempt to initialize it, a TypeScript error occurs. class Bar ext ...

What is the best method for synchronizing the end_date picker with the start_date picker in an ionic2 app and vice versa

My goal is to dynamically adjust the end date picker based on the user's selection of the start date, and vice versa if the user decides to choose the end date first. Here is the code I have written: <ion-item> <ion-label>Start ...

Error: The class you are attempting to access is

Currently, I am utilizing Vite.js along with TypeScript. My TypeScript file is located in 'src/vmodel/VGraph'. Within the index.html file, I import the aforementioned file as follows: <script type="module" src="/src/vmodel/VGrap ...

What is preventing the removal of the zeros during the process of combining a sorted array?

I've been tackling this challenge: Below you'll find the code I've come up with so far: /** Do not return anything, modify nums1 in-place instead. */ function merge(nums1, m, nums2, n) { nums2.forEach(i => { if (i > 0) ...

The View is not reflecting changes in the Variable

Is there a way to disable all the buttons when selectedplace is null in the Dialog, as it currently works when the Dialog first starts but remains activated all the time when the option is changed? I have attempted the following: Customized HTML: ...