Tal Humy
Tal Humy

Reputation: 1227

Angular - How to use arrow functions with arguments?

I have a angular 4 app, and i'm trying to write a queue of actions. each action will be fired after the previous function finished and will get its 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 acitons
    actionsToPerformByOrder.forEach(action => {
      curPromise = curPromise
        .then(action)
        .catch(err => this.error.emit(err));
    })

    //Active 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;
    });
  }
}

My problem is that arrow functions doesn't support arguments and using function() {} instead change the this reference.

Upvotes: 1

Views: 1930

Answers (2)

Max Koretskyi
Max Koretskyi

Reputation: 105499

I suggest you use async/await to combine and run your actions. It's easy to read, here is the basic idea, modify it with your specific case:

async function activeRegistrationASync() {
  const actionsToPerformByOrder = [
    async (r) => {
      return Promise.resolve(3)
    },
    async (r) => {
      return Promise.resolve(r + 5)
    }
  ];

  let result;
  for (let action of actionsToPerformByOrder) {
    result = await action(result);
  }
  return result;
}

activeRegistrationASync().then((r) => {
  console.log(r);
});

Upvotes: 0

RidgeA
RidgeA

Reputation: 1546

  1. You can use spread operator like

    (...rest) => console.log(rest)

  2. You can use bind function

    function func (/arguments/) {console.log(this. arguments)}

    let a = func.bind(this)

Upvotes: 0

Related Questions