Continue to fulfill a promise until a specific condition is satisfied, all within the confines of a while loop

My goal is to create a while loop that encapsulates a promise, ensuring that my method runs until a specific condition is satisfied. I've attempted to do this, but unfortunately encountered an issue with infinite promises being generated, eventually leading to a stack overflow.

I am aiming to achieve something similar to the TypeScript code snippet below:

while (responseSuccess === false) {
    myClass.executeScript.then((thisWasSuccessful: boolean) => {
         responseSuccess = thisWasSuccessful;
    });

Although it may seem unconventional, the script I have developed sends a request to the server which the application typically handles. There are cases where the request does not return success on the first attempt, or even after multiple tries (which is beyond my control).

Answer №1

After reading through all the responses, I definitely see the potential of incorporating async/await operators for a more efficient implementation. With Typescript 2.1.4 being able to transpile async/await code into ES5, it's a great option to consider.

If you're looking to stick with standard Promises, perhaps this approach could suffice:

this.executeAsync.then(() => {
  // Code to execute after the loop
});

private executeAsync(): Promise<void> {
  return new Promise((resolve) => this.executeAsyncLoop(resolve));
}

private executeAsyncLoop(resolve: () => void): void {
  myClass.executeScript.then((success: boolean) => {
     if(!success) executeAsyncLoop(resolve);
     else resolve();
  });
}

I currently don't have the means to test this in an environment, so apologies in advance if there are any issues with it.

Answer №2

Consider implementing the await operator in your code.

while (responseReceived === false) {
  responseReceived = await myClass.runScript;
});

Hint: It is recommended to use TypeScript version 2.1 or later in order to compile to ES5.

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

Problem with sequential promises

import { Observable } from 'rxjs/internal/Observable'; export function createHttpObservable(url: string) { console.log('Url is', url); return Observable.create(observer => { fetch(url) .then(response => { ...

The type of the object is classified as 'unknown' (2571) while utilizing the map() function with an array containing objects

After researching this error extensively on Google and reading multiple posts, I am still unable to find a solution. I am trying to fetch data from an external API call that has the following signature: const properties: { [x: string]: unknown;} | { [x: s ...

Use a spy to mock a component method using karma and jasmine

Encountering this error message during testing: ERROR: 'Error during cleanup of component' The issue stems from the following code snippet : ngOnDestroy(){ methodCallToMock() } To address this, I need to mock the methodCallToMock() functi ...

Sorry, I cannot complete this task as it involves rewriting copyrighted content

I recently implemented the useRef hook in my scroll function, specifying HTMLDivElement as the type. However, I encountered an issue where I received the error message "Property 'clientHeight, scrollHeight, scrollTop' does not exist on type &apos ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

Issue with Angular2 - namespace webdriver not detected during npm installation

Upon restarting my Angular2 project, I ran the npm install command and encountered this error message: node_modules/protractor/built/browser.d.ts(258,37): error TS2503: Cannot find namespace 'webdriver' Does anyone have insight into the origin ...

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

Can you please provide guidance on setting the return type to React.StatelessComponent?

This code is functioning correctly: import * as React from 'react'; export default (props: any): JSX.Element => { return ( <h1>{props.children}</h1> ) } However, this snippet is causing an error: import * as React from ...

Analyzing a sizable JSON file serving as the data source for a PostgreSQL database

Currently, I am working on a Next.js project that involves a large JSON file (~65,000 lines) serving as data for a Prisma Postgres database. The structure of the file includes entries like the following: [ { "NativeClass": "class-name", "Classes" ...

Troubleshooting Async Issue with Promises in JS/Vue

Greetings and thank you for taking the time to read my query. Within my Vue component, named 'interactiveChart', there is a specific sequence of actions that occur when mounted: I begin by initializing various components such as the db manage ...

Adding a static global constant in webpack dynamically

I'm facing a challenge with adding a global constant to my project using webpack.DefinePlugin. I've successfully added one in the module.exports, but I struggle to do this conditionally. When I declare and use '__VERSION__' in my module ...

Getting a precise element from an array in JSON using Angular 5

I've been struggling to fetch a specific value ("isRight") from a JSON object. I have tried multiple solutions found on stackoverflow and even compared my code with one of them, but I keep getting the value as undefined without any errors. { ...

Arranging the properties of an object following the reduction process

I am currently working on replicating the functionality of an Outlook mailbox by organizing a list of Outlook emails based on their conversation ID. However, I am facing the challenge of needing to sort my list twice - once to order the emails in each grou ...

What are the appropriate Typescript typings for React Components that have the ability to return a string or their child components directly?

What are the suitable types for a React Component that can also output a string or directly its children, in addition to a JSX.Element? For example: type PropsStringExample = Readonly<{ returnString: boolean; }>; type PropsChildrenExample = Readon ...

Issue with Material UI DateTimePicker not submitting default form value

Currently, I am utilizing React for my frontend and Ruby on Rails for my backend. My issue lies in submitting the value from my materialUI DateTimePicker via a form. The problem arises when I attempt to submit the form with the default DateTime value (whic ...

There seems to be an issue with AngularJS promises not triggering the `then` callback upon completion

I have a primary controller responsible for setting variables in the scope that are used by inner controllers. The setup process is asynchronous, so I've wrapped it in a promise. However, the callback is not being executed unless it has already been ...

Having Trouble with Ionic 2's Loading Controller

In my attempt to utilize the recently added LoadingController in this scenario: let loading=this.load.create({ content: "Connexion au serveur Migal en cours..." }); loading.present(); this.http.get(this.urlCheckerForm.value.migalUrl+'/action/Mobi ...

Potential issue with Lodash's _.once function: the possibility of a race condition

Here's an example of code that demonstrates a scenario: const fetch = _.once(myRealFetch) const queue = new PQueue({concurrency: 1000}); queue.add(function() { const result = fetch() // Rest of the code ... }) queue.add(function() { const resul ...

Node JS application facing compatibility issues with Typescript not working as intended

I've been diving into Typescript and recently followed a tutorial on how to integrate it with an express api app. However, I encountered the following error: D:\Development\Node\Ed\TypeScript\src\app.ts:5 const app: Appl ...

Angular is able to successfully retrieve the current route when it is defined, but

Here's the code snippet I am working with: import { Router } from '@angular/router'; Following that, in my constructor: constructor(router: Router) { console.log(this.router.url); } Upon loading the page, it initially shows the URL a ...