Utilizing Arrow Functions with Parameters in Angular

I am currently working on an Angular 4 app and I am attempting to create a queue of actions. Each action should only be executed after the previous one has finished, and each action should receive its own set of parameters.

public activeRegistrationAndSync() {
    let actionsToPerformByOrder = [
       () => this.registrationComponent.activeFormValidators.apply(null, arguments),
       () => this.registrationComponent.register.apply(null, arguments),
       () => this.autoLogin.apply(null, arguments),
       () => this.postLogin.apply(null, arguments),
       () => this.checkout.apply(null, arguments)
    ];

    let defer = new Deferred<void>();
    let curPromise = defer.promise;

    //Build chain of actions
    actionsToPerformByOrder.forEach(action => {
      curPromise = curPromise
        .then(action)
        .catch(err => this.error.emit(err));
    })

    //Execute actions
    defer.resolve();
 }
 
 export class Deferred<T> {
  promise: Promise<T>;
  resolve: (value?: T | PromiseLike<T>) => void;
  reject:  (reason?: any) => void;

  constructor() {
    this.promise = new Promise<T>((resolve, reject) => {
      this.resolve = resolve;
      this.reject  = reject;
    });
  }
}

The issue I am facing is that arrow functions do not support arguments, and using function() {} instead changes the reference of 'this'.

Answer №1

If you're looking for a clean and concise way to sequence asynchronous actions, consider using the async/await syntax in JavaScript. This method allows you to easily combine and execute your tasks one after another. Here's a simple example to get you started - feel free to customize it to suit your specific needs:

async function processTasksAsync() {
  const tasks = [
    async (x) => {
      return Promise.resolve(2)
    },
    async (x) => {
      return Promise.resolve(x * 3)
    }
  ];

  let result;
  for (let task of tasks) {
    result = await task(result);
  }
  return result;
}

processTasksAsync().then((result) => {
  console.log(result);
});

Answer №2

  • One way to implement a spread operator is by using:

    (...args) => console.log(args)

  • Another method is using the bind function:

    function exampleFunction (/params/) {console.log(this.params)}

    let b = exampleFunction.bind(this)

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

Sentry: Easily upload source maps from a nested directory structure

I am currently developing a NextJs/ReactJs application using Typescript and I am facing an issue with uploading sourcemaps to Sentry artefacts. Unlike traditional builds, the output folder structure of this app mirrors the NextJs pages structure, creating ...

Invoke a custom AWS CodeBuild project in CodePipeline using a variety of parameters

Imagine having a CodePipeline with 2 stages structured like this: new codepipeline.Pipeline(this, name + "Pipeline", { pipelineName: this.projectName + "-" + name, crossAccountKeys: false, stages: [{ stageName: &apos ...

Exploring the capabilities of multiple router-outlets and submodules within Angular 5

Despite my extensive review of the documentation and other questions, I am still struggling to find a suitable solution for my project. I decided to steer clear of the named router-outlets option as it results in a less clean URL. It seems that many of the ...

Ensuring that Vue3 Typescript app focuses on input element within Bootstrap modal upon opening

I am facing a challenge with setting the focus on a specific text input element within a modal dialog. I have tried various methods but none seem to achieve the desired outcome. Here is what I have attempted: Attempt 1: Using autofocus attribute. <inpu ...

Angular router link circles back to its originator

I've been working on a basic login page that transitions to a homepage once the user successfully logs in. So far, I've focused solely on the HTML structure of the login component without implementing any code in the corresponding TypeScript file ...

Vercel is encountering difficulty locating a module or type declaration during the construction of a Next.js application

Currently, I'm facing an issue while trying to deploy a Next.js app to Vercel. The package react-swipeable appears to have its own type declarations but the build fails with the following error: Running "npm run build" ... > next build ... Failed t ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Update the second select form's list after choosing an option in the first select form in Angular 4

In my form, I have incorporated two select elements within one form tag. The options in the second select element are dependent on the selection made in the first one. Currently, I have set up this functionality using a template-driven approach, with a (c ...

Proper utilization of ngIf in conjunction with mat-cell

I am attempting to show a specific value only if the item possesses a certain property, but I keep seeing [object Object] instead. Here is my current method: <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDe ...

The pipe property cannot be accessed for the specified type "OperatorFunction<unknown, [unknown, boolean, any]>"

I have set up a data subscription that I want to utilize through piping, but for some reason it's not working as expected. The error message I'm receiving is: The property pipe is not available for type "OperatorFunction<unknown, [unknown, b ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

What is the process for initializing the default/prefilled value of an input element within a mat-form-field when the page loads?

I'm looking to create an HTML element where the default data (stored in the variable 'preselectedValue') is automatically filled into the input field when the component loads. The user should then be able to directly edit this search string. ...

What steps can be taken to troubleshoot a TypeScript-powered Node.js application running in WebStorm?

Seeking advice on debugging a node.js application utilizing TypeScript within WebStorm - any tips? ...

Angular's table data display feature is unfortunately lacking

Below is a simple HTML code snippet: <div class="dialogs"> <div id="wrapper" > <p>{{createTestingConstant()}}</p> <ng-container *ngFor="let one of contacts"> <p>{{one ...

What advantages does subscribe() offer compared to map() in Angular?

I recently started exploring observables in angular2 and found myself puzzled over the decision to use map() instead of subscribe(). Let's say I am fetching data from a webApi, like so: this.http.get('http://172.17.40.41:8089/api/Master/GetAll ...

Ordering a list of IP addresses using Angular Material table sorting

Here is an example I am baffled by the fact that Material Table sorting does not properly arrange the table. I have created a stackblitz example to demonstrate this. Expected order - Sorting lowest IP first: "10.16.0.8" "10.16.0.16" & ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

Exploring Iteration of TypeScript Arrays in ReactJS

Issue Encountered: An error occurred stating that 'void' cannot be assigned to type 'ReactNode'.ts(2322) The error is originating from index.d.ts(1354, 9) where the expected type is related to the property 'children' defi ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

In TypeScript, there is a curious phenomenon where private properties seem to be mimicking the

Here is an example of an issue I encountered while working with private properties in TypeScript. I expected that only the public properties would be visible in my object output, similar to normal encapsulation. My aim here is to include the property wit ...